How to get specific columns using with method in laravel Eloquent relationship
How to get specific columns using with method in laravel Eloquent relationship
In this tutorial, we will try to find the solution to "How to get specific columns using with method in laravel Eloquent relationship" through programming.
-
Select specific columns using with() method on Eloquent relationships in laravel
--PATH app\Http\Controllers\<YourController.php>$data = Post::where('status', 1) ->with(['comments' => function($query) { $query->select('id','body'); }])->get();
To use with() method in Laravel, models need to be already connected (one to many, many to many...) with relationships. If they are not connected please Check here to how to make relation. We have to first place a comments method on the Post model to define the relationship between these two models. Now we can select specific columns from the comments table which we want to select using the select method on query builder.
By default with() method gives you all fields from tables which in many cases we do not need. So using this code snippet we can select the specific column from the comments table which is required to us. This code snippet returns all the posts with all related comments with particular columns to every post which status is 1.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Laravel
- Composer\Exception\NoSslException
- How to get route name on visit URL in laravel
- Laravel csrf token mismatch for ajax POST Request
- Laravel append URI in route
- Datetime field in Laravel migration
- Trying to get property 'title' of non-object
- JQuery each loop on json response after ajax in laravel
- Generate unique username in Laravel
- How to get records in random order in laravel
- Ignore Records where a field has NULL value in Laravel
- How to send ID to another page in Laravel
- Retrieve count of nested relationship data in Laravel
- How to create controller in laravel
- Add class to body in laravel view
- How to check record exist or not in relationship table
- Get id of last inserted record in laravel
- Retain selected value of select box in Laravel
- Array to string conversion laravel blade
- How to get all route list
- Redirect to previous page or url in laravel
- Laravel 9 route group with controller
- Define variable and use in Laravel controller method
- How to implement toggleLike() method in Overtrue\LaravelLike laravel package
- Recursive function example code PHP Laravel
- Get posts belongs to a specific user in Laravel