How to get specific columns using with method in laravel Eloquent relationship

Answers 1
  • 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();
    
    0

    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.

  • Back to code snippet queries related laravel