HANZO SALAH HANZO SALAH - 5 months ago 33x
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){

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


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:


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:




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