Reputation: 49
I am trying to query some informations with laravel 4 blade syntax but I am always getting this error:
Trying to get property of non-object
Controller
<?php
class ProfileController extends BaseController {
public function user($username) {
$users = User::where("username", "=", $username);
if($users->count()) {
$users = $users->first();
return View::make("profile.user")->with("users", $users);
} else {
return View::make("404");
}
}
}
user.blade.php
@extends("layout.main")
@section("content")
@foreach($users as $user)
{{$user->id}}
@endforeach
@stop
How can I fix it?
Upvotes: 1
Views: 3105
Reputation: 3664
I think you should do:
$users = User::where("username", "=", $username)->get();
Also you are using first
so
$users = $users->first();
will store only the first user in users variable, so you can't foreach loop it - just remove the line with first
.
Upvotes: 1
Reputation: 22862
Here, you get just the very first row that is (possibly) found
$users = $users->first();
Then, you pass it to view as users
variable (wrong naming, why users, if taking just one?)
return View::make("profile.user")->with("users", $users);
Forget naming right now, here is the problem.
You take !!! one !!! record but you try to itterate it like it is collection of records.
@foreach($users as $user)
{{$user->id}}
@endforeach
Since you try to itterate $users
(which is single user), Laravel will itterate its attributes instead. To solve this, get rid of @foreach
loop and just print what you need to print -> {{ $users->id }}
(and rename that variable, please:)
Upvotes: 0
Reputation: 4490
Seems like its not an object. Try
$user['id']; //In this case its an array
Other, try to output your $user so you can see whats in it. Is there even data in it?
Upvotes: 1