HANZO SALAH HANZO SALAH - 2 years ago 149
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download