Posts Learn Components Snippets Categories Tags Tools About
/

Laravel Route Model Binding Select Only Some Columns

Learn how to select only some columns in route model binding

Created on Jul 13, 2021

638 views

When you have a Route Model Binding in Laravel 8, by default it will retrieve all of the columns of the particular model. If you want to only retrieve some columns then you can make use of the "only()" method provided by the model instance.

Imagine you have an "Article" model and to only retrieve the "id", "title", and "content" you can write it like the following.
<?php

# App\Http\Controllers\ArticleController.php

public function show(Article $article)
{
    $a = $article->only(["id", "title", "content"]);

    dd($a); /* only contain "id", "title", "content" columns */
}

So now instead of getting all of the columns, you can explicitly specify to only retrieve the column you need it to.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)