orchidsoftware / crud

Simplify the process of building CRUD (Create, Read, Update, Delete) functionality in Laravel using the features of Orchid.
https://orchid.software
MIT License
137 stars 34 forks source link

Access authenticated user to fill resource foreign key #66

Closed Bricklou closed 2 years ago

Bricklou commented 2 years ago

I'm trying to add a post management with resources, but I didn't understand how to get the current user ID from my PostResource itself. I saw that there is a onSave method, but there is nothing about getting the user ID from resources objects.

My post object has a foreign key to user.id named user_id and I would like to fill it when I create a new post. How can I do that ?

Bricklou commented 2 years ago

I found what I wanted with this post: https://github.com/orchidsoftware/platform/discussions/1751. I just added the following code:

/**
 * Action to create and update the model
 *
 * @param ResourceRequest $request
 * @param Model           $model
 */
public function onSave(ResourceRequest $request, Model $model)
{
    $data = $request->all();
    $data['user_id'] = auth()->user()->id;
    $model->forceFill($data)->save();
}

Thanks for making this library.