Coder Perfect

On this collection instance, roperty [title] does not exist.


I’m watching Laracasts’ Basic Model/Controller/View Workflow videos.

I have a table where I keep track of people’s contact information.

CREATE TABLE `about` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Using the following code in the controller file, I’m attempting to pass data to view:

public function index()
    $about = Page::where('page', 'about-me')->get(); //id = 3

    return view('about', compact('about'));

When I try to display the code as shown below, it doesn’t work.


    {!! $about->content !!}

I get an error message that says:

It works, though, if I alter the retrieving method in the controller code.

public function index()
    $about = Page::find(3);

    return view('about', compact('about'));

The data is contained by an array when I use dd($about) in the first example (where()->get()). It presents data as expected in the second example (find(3)).

What am I doing incorrectly?

Asked by zkanoca

Solution #1

You get a collection when you use get(). To obtain properties, you must iterate over it in this case:

@foreach ($collection as $object)
    {{ $object->title }}

Alternatively, you might get one of the objects by its index:

{{ $collection[0]->title }}

Alternatively, obtain the first object from the collection:

{{ $collection->first() }}

You get an object when you use find() or first(), thus you can get attributes with simple:

{{ $object->title }}

Answered by Alexey Mezenin

Solution #2

Instead of getting a collection (all data that matches the query) with the get() function, try using first(), which returns only one element, as shown below:

$about = Page::where('page', 'about-me')->first();

Answered by Alex

Solution #3

$about = DB::where('page', 'about-me')->first(); 

instead of obtaining ().

It works on my project. Thanks.

Answered by Phantih

Solution #4

This is a valid syntax that someone might encounter while dealing with factory functions:

$user = factory(User::class, 1)->create()->first();

If you perform something like this, you can get a collection instance error.

$user = factory(User::class, 1)->create()->id;

as a result, update it to

$user = factory(User::class, 1)->create()->first()->id;

Answered by agm1984

Solution #5

In the controller, you should use the Collection keyword. As in this case.

public function ApiView(){
    return User::collection(Profile::all());

User is the Resource Name, and Model is the Model Name. Thank you very much.

Answered by Pnj Patel

Post is based on