T
T
Twelfth Doctor2017-05-07 09:49:56
Laravel
Twelfth Doctor, 2017-05-07 09:49:56

Laravel DB. How to work with objects?

Hello! Can you tell me how to work with objects returned by the DB class in Laravel?
Those. how, for example, to get the name (firstname) of the user with ID 1 from the object returned by the get() function?

<?php

require_once('database.php');

use Illuminate\Database\Capsule\Manager as Capsule;
$result = Capsule::table('user')
    ->where('userid',  1)
    ->get();
print_r($result);

Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => Array ( [userid] => 1 [login] => raven [password] => 827ccb0eea8a706c4c34a16891f84e7b [phone] => +70000000000 [email] => [email protected] [firstname] => Ivanov [lastname] => Ivan [patronymic] => Ivanovich [role] => admin [sessionid] => 0 ) ) )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D3lphi, 2017-05-07
@verdex

In the loop, iterate over the elements of the collection and access them as an object:

foreach($result as $item) {
    echo $item->id;
}

Well, or, like this: If you use the first() method instead of get(), you can access the fields like this: Since in this case the system will be "sure" that it has "pulled out" only one row from the database. It's not in the documentation, is it?

P
pantagruel964, 2017-05-07
@pantagruel964

$user = User::where('userid', 1)->first();
dd($user->firstname);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question