jeudi 13 octobre 2016

Trying to get property of non-object in Laravel Relationship

I have two tables in my database, an Articles table and a Users table. An Article is posted by a user and a foreign key exists called 'created_by' referring to the 'user_id' field in the Users table.

My Laravel models are as follows:

User model

class User extends Model
{
   use Notifiable;

   protected $primaryKey = 'user_id';

   public function articles()
   {
       return $this->hasMany('App\Article', 'created_by', 'user_id');
   }

}

Article Model

class Article extends Model
{

   protected $primaryKey = 'article_id';

   public function user()
   {
       return $this->belongsTo('App\User', 'created_by' 'user_id');
   }

}

I have a view dashboard which displays all the articles and the name of the person who posted it and their image.

Dashboard Controller

<?php

namespace App\Http\Controllers;

use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index (Request $request) 
    {
        if($request->session()->get('username')) {

            $articles = Article::all();

            return view('dashboard', compact('articles'));

        }
        else
            return redirect('login');

    }
}

And finally the section of my view I'm getting the 'Trying to get property of non-object' error for.

@foreach($articles as $article)
        <div class="row">
            <div class="col-lg-1"></div>
                <div class="col-lg-9">
                    <div class="panel panel-info">
                        <div class="panel-heading">
                            <h3 class="panel-title">                                    </h3>
                        </div>
                        <div class="panel-body">
                            <p>
                            
                            <br><br> - 
                            </p>
                        </div>
                    </div>
                </div>
            <div class="col-lg-1"><center><br><br>
                <img src="" class="img-circle" alt="Person"></center>
            </div>
        </div><br><br>
    @endforeach

It seems to be the $article->user->first_name that I am having trouble with. If I type $article->user alone, the page will load but nothing appears in that area.

Any ideas, I have been searching for solutions for the last two hours.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire