michael abraham
michael abraham

Reputation: 47

ErrorException Invalid argument supplied for foreach()

So i was trying to get a full post from the database by id, so when i click this link <a href="{{ route('post.read', ['blog_id' => $blog->id]) }}" class="read-more">Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/></a> it will take me to the url /post/read/{id} and give me the fullpost, but it shows that error,

i search for the same problem and found that that the problem is $blogs variable is an array, but the value it return is not, can anybody show me how to make the method or the view in my code to return an array and show the full post ?

this is my view read.blade.php

@foreach ($blogs as $blog)
                <div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y')  }} /  di <a href="">Rakitan</a></div>
                    <h3>{{ $blog->name }}</h3>
                    <p>{!! $blog->message !!}</p>
@endforeach

this is my BlogController.php

public function getFullPost($blog_id) {
        $blogs = Blog::all()->where('blogs.id', '=', $blog_id)->first();
        return view('post.read')->with(compact('blogs'));
    }

this is the model Blog.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    protected $fillable = ['name','message'];
}

and this is the routes

Route::get('/post/read/{blog_id}', 'BlogController@getFullPost')->name('post.read');

Upvotes: 2

Views: 488

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34924

Use 'get' method to get all rows with cobditions

  public function getFullPost($blog_id) {
    $blogs = Blog::where('id', '=', $blog_id)->get();
    return view('post.read')->with(compact('blogs'));
  }

Add table name in Model to reference in Blog model

Upvotes: 1

Related Questions