Shafee Shafee - 2 years ago 156
PHP Question

Laravel 5.2 : Fetch records against logged in user id

I am fetching records in controller :

$tasks = Task::where('user_id', '=', Auth::user()->id);

return view('todo',compact('tasks'));

But it returns null.

Which is Okay.

Am i missing something ?

Answer Source

You need to actually retrieve the record. What you have is an instance of \Illuminate\Database\Eloquent\Builder, but not the actual record(s) associated with the query.

To tell Eloquent to fetch the data, you need to use either get().


$tasks = Task::where('user_id', '=', Auth::user()->id)->get();

As a side note, you can simplify your query to be:

$tasks = Task::where('user_id', Auth::user()->id)->get();

Furthermore, on your User model, you could do this:

public function tasks()
    return $this->hasMany(Tasks::class) // make sure you use the full namespace here or use at the top of User.php

And then you can simply do:

$tasks = auth()->user()->tasks;

This is a Relationship in Eloquent as explained in the docs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download