0

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
Maqsud
  • 739
  • 3
  • 12
  • 35

3 Answers3

1

The find method looks like this

public function find($id, $columns = ['*'])
{
    if (is_array($id) || $id instanceof Arrayable) {
        return $this->findMany($id, $columns);
    }

    return $this->whereKey($id)->first($columns);
}

This method returns first, so you need to do this $user = User::find(1); and this will return the user.

1

find() give you a model instance, where findOrFail() give you a model instance + it will raise a 404 error if data is empty :

$user = User::findOrFail(1);

A user hasMany posts(), so you need to make a loop to get the data. Before check if the relation has data, otherwise it will throw an error :

if($user->posts()->exists()) {
   foreach($user->posts as $key => $value){
          echo $value->title;
   }
}
Maqsud
  • 739
  • 3
  • 12
  • 35
STA
  • 30,729
  • 8
  • 45
  • 59
0

I'd like to give credit to Original Answer.

The get() will give collections and first() gives objects. Hence, I've used first() method with with('relation') method which accept relation name as parameter.

We can access it by using its index with [] operator

        $user = User::with('posts')->first(); 
        
        $title = $user->posts[0]->title;
        $name = $statements->name;

Maqsud
  • 739
  • 3
  • 12
  • 35