Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel nova resource extending/overriding the create method

I am developing a web admin panel using Laravel Nova.

I am having an issue since Nova is quite a new technology.

What I would like to do now is I would like to add a hidden field or extend or override the create method.

This is my scenario. Let's save I have a vacancy nova resource with the following field.

public function fields(Request $request)
{
    return [
        ID::make()->sortable(),
        Text::make('Title')->sortable(),
        Text::make('Salary')->sortable()
        // I will have another field, called created_by
    ];
}

Very simple. What I like to do is I want to add a new field called created_by into the database. Then that field will be auto filled with the current logged user id ($request->user()->id).

How can I override or extend the create function of Nova? How can I achieve it?

I can use resource event, but how can I retrieve the logged in user in the event?

like image 341
Wai Yan Hein Avatar asked Sep 18 '18 15:09

Wai Yan Hein


People also ask

What is the difference between Nova and Laravel models?

Like Laravel Models are created within the app folder, Nova creates resources within the app/Nova folder. Not really a fan of this, because it gets clumsy when the size of the project grows and you have a lot of resources. My recommendation is to create domain-specific folders inside the folder app/Nova and create resources within them.

What is Laravel Nova Resources?

Building custom tools for Nova Resources. Laravel Nova is an awesome administration for Laravel built by the creators of Laravel. Nova was built to quickly create CRUD screens in the most productive manner.

What is a resource class in Laravel?

A resource class represents a single model that needs to be transformed into a JSON structure. For example, here is a simple UserResource resource class: * Transform the resource into an array.

How to group resources into categories in Laravel?

Laravel provides a way to group these resources into categories and makes a 2 level menu on the sidebar. The $group variable accepts a string and will take the title of the group name.


1 Answers

In my opinion you should go for Observers. Observers will make you code more readable and trackable.

Here is how you can achieve the same with Laravel Observers.

AppServiceProvider.php

public function boot()
{
    Nova::serving(function () {
        Post::observe(PostObserver::class);
    });
}

PostObserver.php

public function creating(Post $post)
{
    $post->created_by = Auth::user()->id;   
}

OR

You can simply hack a Nova field using withMeta.

Text::make('created_by')->withMeta([
    'type' => 'hidden',
    'value' => Auth::user()->id
])
like image 162
Fawzan Avatar answered Sep 22 '22 09:09

Fawzan