Left & right join in laravel

Left & right join in laravel

  • Friends, join is a very important chapter, it is done during operation in Laravel and PHP. With the help of join, we can write complex queries very easily and can get the data very easily.
  • Join is done when we have more than one table and all those tables have some column which is related to each other.
  • As I will explain it to you with a very simple example, I have a table named users in which there are many users and I have another table named posts in which those users have written their posts.
  • Now if I want to get the post according to the user, then I will have to create a field in the post table, I will have to create a column in which the user ID can be stored. So what will happen is that I will match the ID from the user ID table and the user ID column from the post ID table and on that basis I will run phase and operation and get my data.
  • So let’s understand some practical examples of join.
$users = DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();


$users = DB::table('users')
->rightJoin('posts', 'users.id', '=', 'posts.user_id')
->get();

 

Leave a Reply