How to join two tables in laravel?

by darrion.kuhn , in category: PHP Frameworks , 23 days ago

How to join two tables in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 22 days ago

@darrion.kuhn 

To join two tables in Laravel, you can use the join method provided by the Eloquent ORM. Here's an example of how to join two tables in Laravel:

1
2
3
4
5
6
7
8
$users = DB::table('users')
            ->join('posts', 'users.id', '=', 'posts.user_id')
            ->select('users.*', 'posts.title as post_title', 'posts.content as post_content')
            ->get();

foreach ($users as $user) {
    echo $user->name . ' - ' . $user->post_title . ' - ' . $user->post_content;
}


In the example above, we are joining the users table with the posts table on the user_id column. We are selecting the name column from the users table and renaming the title and content columns from the posts table to post_title and post_content respectively.


You can customize the join conditions and select columns based on your specific requirements. Remember to import the DB facade at the top of your file for the above code to work.