How to get user data related to the same model in Laravel

0

How can I get the data of another user, which is referenced from the same user model in Laravel?

Keeping in mind that user has these columns in their migration:

Schema::create('users', function (Blueprint $table) {   

    $table->increments('id');

    $table->string('name');
    $table->string('surname')->nullable();
    $table->string('email');
    $table->string('password');
    $table->rememberToken();

    $table->integer('banned_by')->unsigned()->nullable();
    $table->foreign('banned_by')->references('id')->on('users');
    $table->timestamp('banned_at')->nullable();

    $table->integer('created_by')->unsigned()->nullable();
    $table->foreign('created_by')->references('id')->on('users');
    $table->timestamps();

    $table->integer('deleted_by')->unsigned()->nullable();
    $table->foreign('deleted_by')->references('id')->on('users');
    $table->softDeletes();

    $table->unique(['email', 'deleted_at']);

});

The User model has (among other similar ones) the following method (note that it refers to itself):

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

On the controller:

$user = User::find($id);
return view('ejemplo', compact('user'));

And in the view:

{{ $user->created_by()->name }}

But it returns an error that it is not able to find the property.

    
asked by Sergi C 08.06.2018 в 13:21
source

2 answers

0

Try to get the data like this:

$user = User::with('created_by')->find($id);

And you get the data with:

{{ $user->created_by()->first()->name }}
    
answered by 08.06.2018 в 15:28
0

As in your database you have a field called created_by when using $user->created_by it will return the value you have in the field created_by and not the relation.

On the other hand, if you use $user->created_by() you will return an object belongsTo , since you are directly using the method created_by() .

SOLUTION:

Change the name of your created_by () method to one that is not equal to the name of the fields you have in the database. For example:

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

NOTE:

I see that in the view you use something like this {{ $user->created_by()->name }} , it is not correct, because you are calling directly to your model's method and you are going to return an object belongsTo . The correct thing would be {{ $user->createdBy->name }} Without the parentheses

    
answered by 11.06.2018 в 04:21