Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property [title] does not exist on this collection instance

I am following Laracasts' videos: Basic Model/Controller/View Workflow.

I have a table holds 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 

I am trying to pass data to view using the following code in the controller file:

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

When I try to show the code as shown below,

@section('title')     {{$about->title}} @stop  @section('content')     {!! $about->content !!} @stop 

I get error that says:

Property [title] does not exist on this collection instance. (View: E:\laragon\www\newsite\resources\views\about.blade.php)

But if I change the retrieving method in the controller file, it works.

public function index() {     $about = Page::find(3);      return view('about', compact('about')); } 

When I use dd($about) in the first case (where()->get()) the data is encapsulated by an array. In the second case (find(3)) it displays data as expected.

What am i doing wrong?

like image 837
zkanoca Avatar asked Dec 28 '16 16:12

zkanoca


People also ask

How do I fix property ID does not exist on this collection instance?

You have to retrieve one record with first() not a collection with get() , i.e: $book = $this->bookModel ->join('author', 'author.id', '=', 'book. author_id') ->where('book.id', '=', $id) ->select('book.

Does not exist on type typescript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.


2 Answers

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

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

Or you could just get one of objects by it's index:

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

Or get first object from collection:

{{ $collection->first() }} 

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }} 
like image 109
Alexey Mezenin Avatar answered Sep 20 '22 06:09

Alexey Mezenin


With get() method you get a collection (all data that match the query), try to use first() instead, it return only one element, like this:

$about = Page::where('page', 'about-me')->first(); 
like image 34
Alex Avatar answered Sep 19 '22 06:09

Alex