How to show data from two related tables with laravel?

by jasen_gottlieb , in category: PHP Frameworks , 7 months ago

How to show data from two related tables with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 6 months ago

@jasen_gottlieb 

To show data from two related tables in Laravel, you can use Eloquent relationships. Here's an example with two tables: users and posts, where each user can have many posts.

  1. Define the relationships in your models:


User model:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}


Post model:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}


  1. Fetch data in your controller:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
namespace AppHttpControllers;

use AppModelsUser;

class UserController extends Controller
{
    public function index()
    {
        $users = User::with('posts')->get();

        return view('users.index', compact('users'));
    }
}


  1. Display data in your view:


In your blade view file (users.index.blade.php), you can loop through the users and their related posts like this:

1
2
3
4
5
6
7
8
@foreach($users as $user)
    <h2>{{ $user->name }}</h2>
    <ul>
        @foreach($user->posts as $post)
            <li>{{ $post->title }}</li>
        @endforeach
    </ul>
@endforeach


This will display each user along with their posts in a list format. Make sure to adjust the code according to your actual table structure and field names.