Home > front end >  How to access the value of a Model in Laravel through Controller?
How to access the value of a Model in Laravel through Controller?

Time:04-03

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()

  • 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?

CodePudding user response:

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
  • Related