Laravel Eloquent "has()" Method
The "has()" method is used to check if a relationship exists between 2 models. Imagine having a "Post" model that has a relationship to a "Comment" model. Using the "has()" method you can check if the post has a relation attached to it.
<?php use App\Models\Post; // Get all posts that have at least one comment $posts = Post::query() ->has('comments') ->get();
Laravel Eloquent "whereHas()" Method
The "whereHas()" method is the same as the "has()" method but you can pass in the conditions to query the relation. In the example below, you are performing a query to the "Post" model in which the relation has a body that contains the words "hello".
<?php use App\Models\Post; // Get posts with at least one comment containing words like hello% $posts = Post::whereHas('comments', function (Builder $query) { $query->where('body', 'like', 'hello%'); })->get();
Laravel Eloquent "with()" Method
The "with()" method is used to eager-load an Eloquent relationship to prevent the N+1 problem commonly faced when querying a record. Generally, the use of "with()" method is recommended when you are querying an Eloquent that has a relation.
<?php use App\Models\Post; // Eager-load the comments relation to prevent N+1 problem Post::with('comments')->get(); // If you want to eager-load nested relation then you can use the "." dot notation Post::with('comments.likes')->get();
Laravel Eloquent "load()" Method
Finally the "load()" method is the same as the "with()" method in which it's used to eager-load an Eloquent relationship but the use of this is when you already have an existing eloquent instance for example like below.
<?php use App\Models\Post; // get the first post $post = Post::find(1); // by now it's not possible to call the "with()" method because it's a static method. To eager load at this point you can call the "load()" method from your existing model instance. $post = $post->load("comments'); // now your $post model will have the "comments" relationship loaded as well. dd($post);
Other Reads
Recently Laravel released a method to directly query the relation and you can check out the other snippets from the links below.
Leave a reply