Home » Php » php – Exception in laravel 5.8 : Trying to get property of non-object when trying to edit data

php – Exception in laravel 5.8 : Trying to get property of non-object when trying to edit data

Posted by: admin February 25, 2020 Leave a comment

Questions:

Recently I’ve started with Laravel 5.8 and I’m trying to make the edit button which will update the row from the database. and when the edit button click, Laravel raise an error like this

this is my Controller:

    public function edit($id_book){
        $book = Books::find($id_book);
        return view('/books',['book'->$book]);
    }

    public function UploadEdit(Request $request){
        DB::table('books')->where('id_book',$request->id_book)->update([
            'judul' => $request->judul,
            'gambar' => $request->gambar,
            'kategori' => $request->kategori,
            'deskripsi' => $request->deskripsi,
            'ketersediaan' => $request->ketersediaan,
            'lokasi' => $request->lokasi
        ]);

        return redirect()->back();
    }

this is my models:

    class Books extends Model
    {
        protected $table = "books";
        protected $primaryKey = "id_book";

       protected $fillable = [
           'judul',
           'gambar',
           'kategori',
           'deskripsi',
           'ketersediaan',
           'lokasi'
       ];
    }

I was trying to solve this problem with change edit function in the controller:
from this

    public function edit($id_book){
        $book = Books::find($id_book);
        return view('/books',['book'->$book]);
    }

to this

    public function edit($id_book){
        $book = Books::find($id_book);
        return view('/books',compact('book'));
    }

and this:

    public function edit($id_book){
         $book = Books::find($id_book);
         return view('/books')->withBooks('$book');
    }

but it doesn’t work

How to&Answers:

I think error shows id_book is wrong.
You should use findOrFail() method.

public function edit($id_book){
    $book = Books::findOrFail($id_book);
    return view('/books',compact('book'));
}

Answer:

Change your line 58 (edit() function’s return statement) to:

return view('/books',compact('book'));

Answer:

It seems you used -> instead => to assign value

Change

return view('/books',['book'->$book]);

to

return view('/books',['book' => $book]);

Answer:

Try this

public function edit($id_book) {
   $book = Book::find($id_book);

   return view('books.edit', compact('book'));
}

Answer:

Try this:

 public function edit($id_book){
        $book = Books::where('id_book', $id_book)->first();
        return view('/books', compact('book'));
    }

Answer:

Try this

use findOrFail

public function edit ( $id_book ){
    $books = Books::findOrFail($id_book);
    return view('books',compact('books'));
}