How to auto fill a fk in Laravel using session data?

Asked

Viewed 39 times

1

I have two tables, posts and users. The posts table has a relationship with the users table through the column user_id.

The question is this: in the controller I am using a merge to fill the user_id with the user id. I wonder if it is possible to replace this merge, perhaps by making use of the method user (belongsTo) from the Post model. See the code:

Controller:

$request->merge(['user_id' => \Auth::user()->id]);
Post::create($request->all());

Model Post:

public function user()
{
    return $this->belongsTo('App\Models\User');
}
  • Must give, try: Auth::user()->posts()->create($request->all());. You need to have the model user relationship hasmany with the model Post. https://laravel.com/docs/5.4/eloquent-relationships#the-create-method

  • When I don’t have a session I’m getting the "Call to a Member Function posts() on null" error, however, I’m not being able to handle it with an if. I need to be able to identify whether or not the record was created

  • but how did you do before without a session? What was the user id?

  • I’m sorry, I used the words wrong. In fact I only wanted to prevent an error, for example, if by chance there is no session, fall into a certain condition. For this purpose I have put together the following if => ( Auth::user() & Auth::user()->posts()->create($request->all()))

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.