14

I am trying to create edit page and this error keeps popping up Whoops, looks like something went wrong. Property [id] does not exist on this collection instance. What I've done so far
This is my Route

Route::get('book/edit/{id}', 'BookController@edit')->name('admin.book.edit');
Route::PATCH('book/edit/{id}', 'BookController@update')->name('admin.book.edit');

This is my controller

$books = $this->bookModel
        ->join('author', 'author.id', '=', 'book.author_id')
        ->where('book.id', '=', $id)
        ->select('book.*', 'author.name_1 as authorname1')
        ->get();
    return view('backend.book.edit', compact('books', $books));

Finally view file have the following in form part

{{ Form::model($books, ['route' => ['admin.book.edit', $books->id], 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'PATCH']) }}
<!--form content-->
{{ Form::close() }}

Any help will be appreciated. Thanks

Regolith
  • 2,944
  • 9
  • 33
  • 50

5 Answers5

41

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.*', 'author.name_1 as authorname1')
    ->first();

Please sobstitute $books with $book in the rest of the code also.

dparoli
  • 8,891
  • 1
  • 30
  • 38
6

The error is here:

$books->id

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

@foreach ($books as $book)
    {{ $book->id }}
@endforeach
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
2

I too had the similar error where I was using eloquent relationship, and the problem was I was using return $this->hasMany(ClassName::class); But the relation was of One-to-One so the solution for the problem is return $this->hasOne(ClassName::class);.

Here in above sample the first code segment will return array of objects which will be breakdown the flow of eloquent relation in chained eloquent code like $firstChain->middleChain->requiredData

Here if middleChain has arrayOfObjects it cause above error saying property doesn't exist.

Be careful when using eloquent relation to properly mention the type of relation it has

Afreed A R
  • 41
  • 3
1

I think your code need to update like:

$books = $this->bookModel
       ->join('author', 'author.id', '=', 'book.author_id')
       ->where('book.id', '=', $id)
       ->select('book.*', 'author.name_1 as authorname1')
       ->first();
   return view('backend.book.edit', compact('books'));

Hope this work for you!

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
0

As Mayank mentioned above you get a collection, you neeed to itreate over the FIELDS to get the right field you want. I am giving the same answer in the sytax which is working for me

foreach ($books as $book) {
     $book_id = $book->id
}
DragonFire
  • 3,722
  • 2
  • 38
  • 51