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

Created at 30-Mar-2021 , By samar

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.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

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.