i'm new in laravel. i want to ask is there any other option to access variable in view without using foreach since the return query will always return a single row value.
this is my controller function.
public function publ(Request $request)
{
$id = $request->id;
$user = DB::select("select u.name as name, ut.name as type, ui.info as info from user u
join info ui on ui.id = u.infoid
join usertype ut on u.utype = ut.id
where u.id = ?", [$id]);
if ($user != null) {
return view('index', ['user' => $user]);
}
}
i used this to access it on view.
@foreach($user as $u)
{{ $u->name }}
@endforeach
it works but i just curious about other options.
i've tried using {{ $user[0]['name'] }}
but it shows error Cannot use object of type stdClass as array
.
First of all, you are NOT using Query Builder or Eloquent, you are doing a direct query on the Connection. This will return an array of stdClass
objects. stdClass
objects do not have any "array access" as they are just base level objects; you have to interact with them as objects (accessing properties) not as an array (accessing elements).
Assuming you actually get a result the first result would be accessed as:
$user[0]
The properties of that object would be accessed via the property notation:
$user[0]->name
These are not Models. Eloquent Models implement ArrayAccess
which allows them to be "used" as arrays (using array notation). This is not something that is default for objects.