HANZO SALAH HANZO SALAH - 7 months ago 46
PHP Question

Eloquent ORM relationship on laravel 5

I create messages system on laravel 5, but I cant get sender information on recuperation page (such as name email...)

I have messages table:

public function up()
{
Schema::create('messages', function(Blueprint $table){
$table->increments('id');
$table->integer('destination_id')->unsigned();
$table->integer('source_id')->unsigned();
$table->string('sujet');
$table->text('contenu');
$table->boolean('vu')->default(0);
$table->boolean('repondu')->default(0);
$table->timestamps();
$table->foreign('source_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('destination_id')->references('id')->on('users')->onDelete('cascade');
});
}


On the models I create add this:

Message Model:

class Message extends Model {

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


and on User model I add this function:

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


But when i Try to fetch user messages and want to get for example {{$message->user->name}} I get a error message that I try to get property of non-object

this is the controller to this page

Answer

Well default user's key field when you're using: return $this->belongsTo('App\User'); if a table name is like: table_name_id in this example will be like: user_id.

I see that you need relations to user table on:

$table->integer('destination_id')->unsigned();
$table->integer('source_id')->unsigned();

so the best solution will be to create two methods like:

class Message extends Model 
{
    public function source()
    {
        return $this->belongsTo('App\User', 'source_id');
    }

    public function destination()
    {
        return $this->belongsTo('App\User', 'destination_id');
    }
}

then you can call:

{{$message->source->name}}

and

{{$message->destination->name}}

Of corse you can name this method in other way, like: sourceUser() for example.