Search code examples
phplaraveleloquent-relationship

How to get tasks that match logged in user id?


In Controller:

$user = user()->id;
$tasks = task::with('user')->where('tasks.user_id', '=', '$user')->get();

Task Model:

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

User Model:

public function Tasks()
{
    /**
     * The relationship to the user's tasks.
     *
     * @return HasMany
     */
    return $this->hasMany(Task::class, 'user_id', 'id');
}

Here is the error: Trying to get property 'user_id' of non-object


Solution

  • $user = auth()->user()->id; //This line of code will give Authenticated user id.
    $tasks = task::with('user')->where('tasks.user_id', '=', $user)->get(); //Remove single quate from $user variable
    

    Or

    $user = \Auth::user()->id; 
    $tasks = task::with('user')->where('tasks.user_id', '=', $user)->get();
    

    Hope this will be useful.