PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

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

 April 19, 2022     eloquent, laravel     No comments   

Issue

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?


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


Answered By - Maik Lowrey
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing