How to add a new field in Laravel Nova Resource

Vineeth Vijayan
Vineeth Vijayan
Published in
2 min readJul 10, 2020

--

Almost all web apps need a dashboard. And we developers make CRUDs for users, products, employees etc. Even thought the fields changes, we are doing repeating too many steps in the process. So the idea is to generalise those steps and code only the login which is unique to an entity. Laravel Nova is amazing contribution from Laravel.

Recently I came across a requirement to add a new field to a Laravel Nova resource. The scenario is this:

I have two tables users and posts. Also I have two Nova resources, UserResource and PostResource. In the PostResource, I have fields like name, description, date and tags. Now I need to add a field called author_id which will be hidden in the Create Post form, but it need to be inserted when new Post is created by logined User.

The way I handled this requirement is by using Laravel Observers. Observer classes are model event listeners. So on a new Post create event, we can add a listener function for create action. Please refer following code.

PostResource code
  1. Create an observer class for Post Model with following command:
php artisan make:obeserver -m Post PostObserver
Add this code snippet in newly post observer.

2. Register PostObserver in AppServiceProvider like this:

We are done. This is it.

Now on each create event “author_id” will be inserted before a new Post record is created.

Love this article? Click here to buy me a coffee :)

--

--

Vineeth Vijayan
Vineeth Vijayan

Software Engineer | Scribbler | Loves coding and movies | Passive Reader | Lazy Blogger