K
K
Karpkarp2020-03-06 22:08:55
Laravel
Karpkarp, 2020-03-06 22:08:55

How to solve Laravel pagination and date issue?

Hello. I ran into a display problem in the created_at field template, I needed to display the date the post was created. The date was displayed, but was always the same.

Such a controller

public function index()
    {
        $posts = Blog::join('users', 'author_id','=', 'users.id')
            ->orderBy('blogs.created_at', 'desc')
            ->simplePaginate(15);

        return view('posts.blog', compact('posts'));
    }

In the template, I accessed the field like this {{$post->created_at->diffForHumans()}}

I noticed a jamb with the date and changed the controller
public function index()
    {
        $blogs = Blog::join('users', 'author_id','=', 'users.id')
            ->orderBy('blogs.created_at', 'desc')
            ->simplePaginate(15);

        return view('posts.blog', compact('blogs'));
    }

Yes, I just $postsreplaced it with $blogs
As a result, the problem with the date was solved, but when adding pagination, {{ $blogs->links() }}an error occurs
Method Illuminate\Database\Eloquent\Collection::links does not exist. (View: W:\domains\blog\resources\views\posts\blog.blade.php)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex Wells, 2020-03-06
@Alex_Wells

And you look at your query, mb you will notice that it pulls out a bunch of fields with the same names....

K
Karpkarp, 2020-03-06
@Karpkarp

I decided so, it seems to work, but somehow it doesn’t turn out beautifully

public function index()
    {
        $blogs = Blog::join('users', 'author_id','=', 'users.id')
            ->orderBy('blogs.created_at', 'desc')
            ->get();

        $paginateBlog = Blog::paginate(10);

        return view('posts.blog', compact('blogs', 'paginateBlog'));
    }

V
Vyacheslav Plisko, 2020-03-10
@AmdY

Yes, you read the documentation, you will find how Eloquent works with relationships, then the code will be in one line

return view('posts.blog', 
[
'blogs' => Blog::with('user')->orderBy('created_at')->paginate(10)
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question