
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
- Cast Array to an Object in Controller and then pass to view in laravel
- Get current month records in laravel 7/8
- How to fetch single row data from database in laravel
- How to display order by null last in laravel
- How to generate .env file for laravel?
- Create model with migration and seeder
- Get today records in Laravel
- Credit card validation in laravel
- Post model with title and body in laravel 8
- Delete records with relationship in laravel
- Print query in laravel
- Laravel append URI in route
- Route not defined in Laravel
- How to pass query string with pagination in laravel
- On delete set foreign id column value null using migration in laravel 8
- FirstOrCreate() Not Inserting Model
- Connection could not be established with host smtp.gmail.com :stream_socket_client(): unable to connect to tcp://smtp.gmail.com:587 (Connection refused)"
- Get duplicate records in laravel
- Create records using relationship in laravel
- Skip first n record and display rest records in laravel view
- How to create laravel project using composer
- The POST method is not supported for this route. Supported methods: PUT.
- How to show data by ID in laravel?
- Remove public from url in laravel project
- How to add unique records in pivot columns of Laravel pivot table