How to access related table in laravel?

by hal.littel , in category: PHP Frameworks , 4 months ago

How to access related table in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@hal.littel 

In Laravel, you can access related tables using Eloquent relationships. Here's an example of how to access a related table in Laravel:


Assuming you have two tables: 'users' and 'posts', where 'users' has many 'posts', you can define a relationship between the two tables in the User model like this:

 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);
    }
}


Then, you can access the related 'posts' table in your controller or view like this:

1
2
3
4
5
6
$user = User::find(1);
$posts = $user->posts;

foreach ($posts as $post) {
    echo $post->title;
}


This will retrieve all the posts associated with the user with ID 1 and print out their titles. You can also eager load the related table using the with method:

1
2
3
4
5
6
$user = User::with('posts')->find(1);
$posts = $user->posts;

foreach ($posts as $post) {
    echo $post->title;
}


This will load the posts along with the user in a single query, improving performance. You can also access related tables in blade templates using the same method.


That's how you can access related tables in Laravel using Eloquent relationships.