Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the value of a Model in Laravel through Controller?

I’m trying to get an ‘id’ of the table where ‘user_id’ == auth()->id() (checks what row belongs to user).

here’s what I accomplished so far:

  • In the Controller with this line I’m trying access ‘id’ of Clients table where…
    'client_id' => Clients::select('id')->where('user_id', auth()->id())->get()

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • Once Controller is triggered it gets the ‘id’ as an object and tries to insert into DB as:
    [ { "id": 1 } ]

What would be an overcome to this, so I can get only ‘id’ value in return?

>Solution :

get() will returned a collection. You can use instead first() then you have directly access to the Model. Afterwards you can append ->id. It will return only the client id.

'client_id' => Clients::select('id')->where('user_id', auth()->id())->first()->id;

// output the id as int
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading