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.