How to get Last Record From leftJoin Table in Laravel7?

  1191 views   2 years ago Laravel

In this article i will share with you one of the helpful laravel database query solution with simple example. we have two following tables for solve this laravel query problem.

articles table structure

| id | title | slug | body | tags_id | categories_id |
|    |       |      |      |         |               |
|    |       |      |      |         |               |
|    |       |      |      |         |               |

comments table structure

| id | article_id | comment |
|    |            |         |
|    |            |         |

Challenge :

Here, chalange is get all the records from articles table. but, also get the latest/last comment from comments table. here we want only new comments not the all comment will get in the records.


Here we have 2 tables 'articles' and 'comments' where articles is left table and comments is right table which has article's comments.

We wanted to left join articles with comments but the join should be with the latest record from comments table.

$query = Article::select('articles.*', 'comments.comment as article_comment')
->leftJoin('comments', function($query) {
        ->whereRaw(' IN (select MAX( from comments as a2 join articles as u2 on = a2.article_id group by');

I hope this laravel query solution more helpful to you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]