get Last Record From leftJoin Table in Laravel?

get Last Record From leftJoin Table in Laravel?

In this post we will give you information about get Last Record From leftJoin Table in Laravel?. Hear we will give you detail about get Last Record From leftJoin Table in Laravel?And how to use it also give you demo for it if it is necessary.

get the latest record from leftJoin table, how to get the last record from letjoin table in laravel, in laravel whereRaw() example, nested join in join example, self join in laravel,


In this article, I will share with you one of the helpful laravel database query solutions with a simple example. we have two following tables to 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, the challenge is to get all the records from articles  table. but, also get the latest/last comment from comments  table. here we want only new comments not all comment will get in the records.


Solutions


Here we have 2 tables ‘articles’ and ‘comments’ where articles is left table and comments is the right table which has an 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) {
    $query->on('comments.article_id','=','articles.id')
        ->whereRaw('comments.id IN (select MAX(a2.id) from comments as a2 join articles as u2 on u2.id = a2.article_id group by u2.id)');
})
->get();


I hope this laravel query solution more helpful to you.

Hope this and post will helped you for implement get Last Record From leftJoin Table in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

2  +  5  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US