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 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.
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.
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.
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.
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
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With