Laravel: Display Row() instead of result()

Asked

Viewed 21 times

1

I’m wearing the Laravel 7.3. I have the following appointment:

$data = DB::table(self::TABLE_CATEGORIES)
        ->select('id')
        ->where('slug', $slug)
        ->get(); 

And the result would be this:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 10
                )

        )

)

And I would like to get only the result

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [id] => 10

        )
)

In this case, when I do echo $items->id, I would have the result, but the previous way I would have to use a foreach() to get the result.

How can it be done?

1 answer

1


You can use the method pluck()

<?php
DB::table('...')
    // ...
    ->pluck('id');

P.S.: with Laravel it is recommended to have a Model for each table, so you do not need to pass the table name in all calls. If there was a Model Categories could call with Categories::pluck('id').

Browser other questions tagged

You are not signed in. Login or sign up in order to post.