
laravel hasmany select not working
There could be any reason for select query on hasMany() relation not working. We provide code snippet to select the specific column using with method on eloquent relationships in laravel.
-
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();
0To 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.
Random Code Snippet Queries: Laravel
- Generate unique username in Laravel
- How to get all posts which contains comments in laravel
- Validation errors for multiple forms on same page Laravel
- Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request
- How to add columns in existing table using migration in laravel
- Target class [App\Http\Controllers\Auth\Request] does not exist.
- Skip first n record and display rest records in laravel view
- How to insert value to additional columns in pivot table in laravel
- How to display validation error in laravel
- Create project table with model and migration
- Laravel recursive function in controller
- How to check data inserted or deleted in pivot after toggle method
- Rendering HTML from database table to view in Laravel
- How to get only time from created_at in laravel
- How to create and run user seeder in laravel
- Method Illuminate\Database\Eloquent\Collection::appends does not exist
- How to return a column with different name in Laravel
- Convert input array to comma-separated string in laravel controller
- How to insert ckeditor data into database in Laravel?
- Recursive function example code PHP Laravel
- Trying to get property 'title' of non-object
- How to check query string exists or not in laravel blade
- Insert dummy data in users table Laravel
- How to get specific columns using with method in laravel Eloquent relationship
- Laravel create table migration with model