Dax
Dax

Reputation: 827

Not getting the newest records with latest() in Laravel

Here is my code that handles the database request to the view:

public function index()
{
    $user = User::find(Auth()->id());
    $tasks = Task::latest()->get();
    $comments = Comment::all();
    return view('layouts.index', compact('tasks', 'user', 'comments'));
}

This displays all the tasks that one user has with the related comments for each post. Before I added the $user variable with the id of the user, I received all the newest tasks before the old ones. This is not the case anymore.

$tasks = Task::latest()->get();

Why am I getting my oldest records before the newest ones?

My view:

 @if (count($tasks) > 0)
                @foreach($user->tasks as $task)
                    <div class="tasks">
                        <a href="{{ route("tasks.show", ["id" => $task->id]) }}"><h4><strong>{{$task->title}} </strong></h4></a> 
                        <p>Description: {{$task->description}}</p>
                        <strong>Task created: {{$task -> created_at -> diffForHumans()}}</strong>
                        <hr>
                        <p>{{count($task->comments)}} comments</p>
                        <a href="{{ route("tasks.edit", ["id" => $task->id]) }}"><button class="btn btn-outline-light">Edit</button></a> 
                        {!! Form::open(['action' => ['TasksController@destroy', $task->id],'method' => 'POST', 'class'=> 'float-right']) !!}
                            {{Form::hidden('_method','DELETE')}}
                            {{Form::submit('Delete', ['class' => 'btn btn-outline-danger'])}}
                        {!! Form::close() !!} 
                    </div>
                @endforeach  

Working version:

 $user = User::where('id',Auth()->id())->with(['tasks' => function ($query) {
        $query->latest();
    }])->first();

    $comments = Task::where('user_id',Auth()->id())->with(['comments' => function ($query) {
        $query->latest();
    }])->first();


  return view('layouts.index', compact('user', 'comments'));

Upvotes: 0

Views: 229

Answers (1)

Camilo
Camilo

Reputation: 7184

You are iterating over $user->tasks instead of $tasks, which is not being ordered. That's why you are seeing the oldest results first.

To order $user->tasks you could use eager loading:

$user = Auth::user();

$user->load(['tasks' => function ($query) {
    $query->latest();
}]);

$user->load(['comments' => function ($query) {
    $query->latest();
}]);

In this example I'm using the Auth facade to retrieve the user.

Upvotes: 1

Related Questions