I have been spending hours searching to find this.
I am very new to Laravel, ( coming from CodeIgniter ) and I am trying to do everything the Laravel way instead of using pure php/sql anywhere unless it is very necessary.
$role_id = Role::select('role_id')
->where('type','Admin')
->get();
var_dump($role_id);
I am trying to fetch $role_id.
The var_dump gives me this.
object(Illuminate\Database\Eloquent\Collection)#249 (1) { ["items":protected]=> array(1) { [0]=> object(App\Role)#252 (26) { ["connection":protected]=> string(5) "mysql" ["table":protected]=> string(5) "roles" ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(true) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(1) { ["role_id"]=> int(99) } ["original":protected]=> array(1) { ["role_id"]=> int(99) } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } } } }
I expected just a mysql result row instead of this.
What I am looking for is just this ["role_id"]=> int(99)
.
I am missing a function to directly get this, and I cant find it from the docs.
$role_id->role_id
gives me property not found.
You have items with get method. This of the reasons cannot access role_id.
You can use first instead of get method if you want to one record.
and you can use dd() function.
$role_id = Role::select('role_id')
->where('type','Admin')
->first();
dd($role_id);
You can do this:
$role_id = Role::all(['role_id'])->where('type','Admin')->first(); or Role::where('type', 'Admin');
Instead of var_dump you can use dd($role_id) or var_dump($role_id), it dies and dumps at the same time .
Use ->first()
instead of ->get()
. get()
returns collection.
This is the right way of doing it.
$response = Role::select('role_id')
->where('type','Admin')
->first();
$admin_id = $response->role_id;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.