DolDurma
DolDurma

Reputation: 17360

Laravel fetch Collection object in view

in below code i have Eloquent command and that return Collection object and i can not fetch that into view.

$collection = DB::table('contents')
    ->join('categories', function($join)
    {
        $join->on('categories.id', '=', 'contents.category');
    })
    ->where('contents.id', '=', $id)
    ->get();

thats return single Collecton Object and i do not need to use foreach. how to fetch this collection object in view without usign foreach?

i get error after using this :

echo $collection->title;
{{ $collection->title }}

ERROR:

Trying to get property of non-object

Upvotes: 0

Views: 1333

Answers (1)

majidarif
majidarif

Reputation: 20085

What is a single collection object? You must be talking about a single model? Collections are always an array of models.

Your query should be like:

$collection = DB::table('contents')
                ->join('categories', 'contents.category', '=', 'categories.id')
                ->where('contents.id', '=', $id)
                ->first();

echo $collection->title;

passing data to the view can be like:

$data = array(
   'collection' => $collection
);
return View::make('collection', $data);

accessing the data from the template:

{{ $collection->title }}

Upvotes: 1

Related Questions