Walker Base
Walker Base

Reputation: 197

Laravel Can't get item in an array

In my blade.php, suppose the post user is the logged in user

@foreach($posts as $post)
        {{$user = App\User::find($post->user_id)}}
        {{$user}}
        {{Auth::user()}}    
@endforeach

Output on page:

{"user_id":"123","email":"123@com","password":"1234","first_name":"Tony"}
{"user_id":"123","email":"123@com","password":"1234","first_name":"Tony"}
{"user_id":"123","email":"123@com","password":"1234","first_name":"Tony"}

If I want to get the first_name only

I change

{{Auth::user()}} to {{Auth::user()->first_name}}

I can get "Tony"

but if I change {{$user}} to {{$user->first_name}}

I got error

"Trying to get property of non-object" (View: C:\PathToProject\resources\views\dashboard.blade.php)

Upvotes: 0

Views: 281

Answers (2)

Jeremy Harris
Jeremy Harris

Reputation: 24579

You are misunderstanding what the double curly brace syntax does in Laravel Blade. When it pre-processes the view, it effectively turns them into an echo statement like this:

// This
{{ $x }}

// Will become this
<?php echo($x); ?>

You can't do assignment logic like you are trying to do within those curly braces because echo isn't a standard function, it is a language construct and doesn't work that way.

The recommended approach is get that value in your controller and pass it to your view. Something like:

return view('dashboard', [
   'user' => App\User::find($post->user_id)
]);

If you absolutely need to get it within the view (not recommended), you will have to fallback to plain old PHP for that:

<?php $user = App\User::find($post->user_id); ?>

And then you can access it.

EDIT


In the case of each post having a user, you should use query scopes to pull the user when you get the posts. Something like:

$posts = Post::withUser()->get();

And your scope might look something like:

function scopeWithUser($query) 
{
    return $query->leftJoin('users', 'users.id', '=', 'posts.user_id');
}

Upvotes: 2

zorx
zorx

Reputation: 1951

You can use this "hack"

@foreach($posts as $post)
        {{--*/ $user = App\User::find($post->user_id); /*--}}
        {{$user->first_name}}
        {{Auth::user()}}    
@endforeach

Upvotes: 0

Related Questions