Unable to access Laravel Eloquent Relationship
While using get() method
$user = User::find(1)->get();
$foo = $user->posts->title;
Property [posts] does not exist on this collection instance.
After using first() method
$user = User::find(1)->first();
$foo = $user->posts->title;
Or
$user = User::with('posts')->first();
$foo = $user->posts->title;
Property [title] does not exist on this collection instance.
Files & Configuration
App\Models\User.php
namespace App\Models;
use App\Models\Post;
class User extends Model
{
public function posts(){
return $this->hasMany(
Post::class,
'post_code',
'code'
);
}
}
App\Models\Post.php
namespace App\Models;
class Post extends Model
{
protected $fillable = ['title', 'code', 'tags'];
}
Post table where id field is PK. But I want to make relation with code field.
| id | title | code | tags |
|---|---|---|---|
| 1 | Monalisa | MH01 | arts |
| 2 | AI | MH01 | science |
User table in which post_code has many relation with Post table.
| id | name | post_code |
|---|---|---|
| 1 | John | MH01 |