Search code examples
phplaravel-5.5

Invalid argument supplied for foreach() Laravel 5.5


I have two tables, users and posts table link together using one to many relationship in Laravel 5.5. I want to only show the posts associated with a login user.

I have PostController where I get current user login and pass it to a view index.php. In index.php view I am trying to get and loop posts associated with a login user using @foreach.

See below my sample codes.

PostController

public function index()
{
    $currentuser = Auth::user();
    return view('posts.index')->withCurrentuser($currentuser);
}

index.php view

@foreach ($currentuser->posts as $post)
        <tr>
            <td>{{ $post->id }}</td>
            <td>{{ $post->title }}</td>
            <td>{{ substr(strip_tags($post->body), 0, 40) }}{{ strlen(strip_tags($post->body))>40 ? "..." : "" }}</td>
            <td>{{ date('M j, Y', strtotime($post->created_at)) }}</td>
            <td><a href="{{ route('posts.show', $post->id) }}" class="btn btn-outline-blue btn-sm">View</a>&nbsp;<a href="{{ route('posts.edit', $post->id)}}" class="btn btn-sm btn-outline-blue">Edit</a></td>

        </tr>

    @endforeach

User.php Model

 protected $table = 'users';
    public function post(){
        return $this->hasMany('App\Post');
    }

Post.php Model

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

I am getting an error

Invalid argument supplied for foreach()

Where could be the problem?


Solution

  • The user model defines the method as post() but in foreach you're calling it ->posts (plural). Try @foreach ($currentuser->post()->get() as $post)