When you make relationship in Laravel eloquent relationship, there are two ways you can access eloquent relationships data. In a lazy loading, when you access the property, then relationships data loaded.
For example, Post model is belongs to User model. So when you want to get all users data with posts records. Here is Post model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the users that write article
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Now we get data in controller.
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name;
}
In eager loading, all the users are also retrived with post records - with()
$posts = Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name;
}
multiple relationships
$posts = Post::with(['user', 'category'])->get();
Nested Eager Loading
$posts = Post::with('user.address')->get();
specific columns
$posts = Post::with('user:id,email,phone,post_id')->get();
I hope everyone enjoys the code.
Top comments (0)