-1

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

Laing
  • 3
  • 5

3 Answers3

0

Auth::user()->id; or Auth::id(); to get the identity of the logged in user; you can use. For detailed information, you can check here: https://laravel.com/docs/8.x/authentication#retrieving-the-authenticated-user

alihancibooglu
  • 167
  • 2
  • 10
0
$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.

Rajen Trivedi
  • 1,225
  • 2
  • 5
  • 10
0

You can simply call

$tasks = Auth::user()->tasks;

and $tasks contains tasks that belongs to the current user

Mohammad Akbari
  • 446
  • 2
  • 9
  • 1
    Mohammad Akbari, that works perfectly but how does Laravel know to go into the User's model and grab the tasks method? – Denis Denchev Nov 30 '21 at 15:08
  • Great question. Excellent. Before answer your question, you must know the laravel request lifecycle. It is truly simple, but I can not explain it to you in comment section. But for clarification, Auth object resolve the authenticated user, then on that object your code call the tasks method which leads to return a relation object that fetch data from database. – Mohammad Akbari Jan 27 '22 at 10:20