eskimo
eskimo

Reputation: 2624

Laravel Eloquent defined relationship not working

In the posts migration:

$table->unsignedBigInteger('created_by')->nullable();
$table->foreign('created_by')->references('id')->on('users')->onDelete('set null');

In the Post model

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

In the controller fetching the posts:

$posts = Post::with('created_by')->get();

In the blade view

{{ $post->created_by->name }}

But I get: Attempt to read property "name" on int as $post->created_by is 1 for instance, but not the full model loaded as a relationship which is what I'm trying to do.

Upvotes: 0

Views: 112

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

As you pointed out in the question, created_by is 1, i.e. the ID representation of the User instance that created the Post instance, and the error properly reflects this (since what essentially equates to 1->name is not valid PHP code). To handle this, use a different name for your relationship than the column being used as the Foreign Key reference:

// `createdBy`, `createdByUser`, `user`, etc. etc., as long as it is different than `created_by`
public function createdBy() {
  return $this->belongsTo(User::class, 'created_by');
}

Method names should be camelCase, createdBy, instead of created_by. Additionally, you don't need the full namespace if they are shared (i.e. App\Models\Post and App\Models\User have the same App\Models namespace, so User::class is all you need in the definition.

Now, with this code, you should be able to call:

{{ $post->createdBy->name }}

Upvotes: 2

Related Questions