Home / Snippets / Laravel Route Model Binding Select Only Some Columns
Laravel Route Model Binding Select Only Some Columns cover

Laravel Route Model Binding Select Only Some Columns

672

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this