I wrote a Controller to send Post Model along with it's Categories and Pics:
class HomeController extends Controller
{
public function index ()
{
$latestPosts =
Post::with([
'latestPicture',
'categories' => function ($query) {
$query->select(['categories.cat_id', 'name']);
}
])
->take(12)->orderBy('created_at', 'desc')
->get(['post_id', 'post_title', 'post_alias', 'post_content', 'comments_count', 'created_at']);
// dd($latestPosts) ;
return view('main.pages.home', ['latestPosts' => $latestPosts]);
}
}
And for use latestPosts in My View I write this:
@if (!$latestPosts->isEmpty())
@foreach($latestPosts as $post)
@if( key($latestPosts) <3)
<!-- Some HTML -->
@endif
@endforeach
@endif
but I faced this Error :
Trying to get property of non-object (View: D:\wamp\www\TC\resources\views\main\pages\home.blade.php)
What is Problem? How Can I access to that Collection in the View?