尝试在laravel中获取非对象错误的属性

问题描述:

ive been trying to match User_id from my users with Creator_id to display the creators username in my post but im getting the trying to get property from non-object error and i cant get arround it

the function in my controller postcontroller.php:

public function index()
    {
    $allusers = users::getusers();

    $posts = DB::table('posts')->get();
    foreach ($posts as $posts) {
        foreach ($allusers as $allusers) {
            if ($posts->creator_id == $allusers->user_id) {
              array_push($posts,$allusers->username); 
            }
        }
    }
     return view('blog',['posts'=>$posts]);   
    }

the functions in my model:

public static function getusers(){
    $allusers = users::all();
    return $allusers;
    }

You are using the same variable names in your foreach loops :

foreach ($posts as $post) {
    foreach ($allusers as $user) {
        if ($post->creator_id == $user->user_id) {
          array_push($post,$user->username); 
        }
    }
}

But for your issue, you should try to add this in your Post Model

public function user(){
    return $this->belongsTo(User::class, 'creator_id', 'user_id);
}

then in your view :

@foreach($posts as $post)
    {{ $post->user->name }}
@endforeach

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse

Does your users table has a column like user_id?

I think you have check with users table id with posts creator_id.