understand collection results from Elequent relationship in blade

Posted 10 months ago by Mrs_Beginner

i want to show posts from a user in his profile...i did this but with some bugs (i can show posts but i cant show user first name) and i cant understand how it works... lets see my code first:

my post model is like below:

class post extends Model
{
    protected $fillable=['user_id','imgurl','name','detail'];

    public function user(){
        return $this->belongsToMany('App\User');
    }
}

then my user model is like below:

class user extends Model
{
    protected $fillable=['firstname','lastname','bio'];

    public function post(){
        return $this->hasMany('App\Post');
    }
}

and then function of my userController that call profile blade is:

 public function userposts($id){
        $user=User::find($id);
        return view(profile.posts',compact('user'));
     }

and finally part of my blade that shows posts and user name is like below code:

this profile belongs to mr/mrs {!! $user->firstname !!}
<tbody>
                @foreach($user->post as $post)
                    <tr>
                        <td> {!! $post->name !!}</td>
                        <td> {!! $post->detail !!}</td>
                        </td>
                    </tr>
                @endforeach
                </tfoot>

ok now i have some questions about this code... 1- in this blade i can see posts lists with their information but {!! $user->firstname !!} in top of blade dont show user first name, i think this line of code can show name but nothing appeared there,

2- if i change my userController code for showing user name to below code:

public function userposts($id){
        $user=User::find($id)->post();
        return view(profile.posts',compact('user'));
     }

but now some errors will happen that i cant understand them correctly its about collections but how they are creating... first error is like below

ErrorException (E_ERROR)
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$firstname

this error points to {!! $user->firstname !!} and says its not exist in this collection. 2-1 how to fix this? or my controller code is not coreect?

2-2 if i delete {!! $user->firstname !!} from blade seccound error will happen is like below code.

ErrorException (E_ERROR)
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$name

this one points to {!! $post->name !!}. i know this one is about collections too but i dont know how to fix it.

some one can explain to me how to handle this problem? how to understand this collection and show them in blade?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.