How to save logged user_id using bread?

Solved
hermesalvesbr

Dec 2nd, 2019 09:15 PM

Hi,

How can i get the user_id (logged user) on save?

I want to know wich user add in table.

Like this: https://github.com/the-control-group/voyager/issues/2969

mark

Dec 3rd, 2019 07:57 AM

Let's imagine you have a Post model, that includes a author_id that you wish to automaticcally set when a post is saved, then you can inside the Post model add the following method:

    public function save(array $options = [])
    {
        // If no author has been assigned, assign the current user's id as the author of the post
        if (!$this->author_id && \Auth::user()) {
            $this->author_id = \Auth::user()->id;
        }

        parent::save();
    }
cookie

Dec 3rd, 2019 08:25 PM

Best Answer

Another possibility... Create a boot method on your Model with the follow content:

``

parent::boot();

static::creating(function($model)
{
	$userid = (!auth()->guest()) ? auth()->user()->id : null;
	$model->author_id = $userid;
});

//created
//updated
//deleted
//and so on .. ;-)

``