Form Model Binding

Normally, Use of model binding when you wish to edit some records. This mechanism is using for display old input value in edit form which returns by primary key or slug.

Let's see use of model binding :

Check Controller app/Http/Controllers/BookController edit method -

<?php
/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
        // find a row by given id and get all columns
        $book = Book::find($id);
       // Redirected to book/editBook.blade.php view
        return view('books.editBook')->with('book',$book);
	}

 

How it works :

{!! Form::model($book) !!}

Look at the above code, It will place every $book value($book→title, $book→description, $book→author) at the right place by itself.

Proper example of form model() with BookController update method.

{!! Form::model($book, ['route' => ['book.update', $book->id ], 'method'=>'PUT']) !!}
	//  Form structure
{!! Form::close() !!}

Above code have an array within model, Where route is redirecting the form values and form method will be put insteadof post for update method.

<?php
/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id, Request $requestData)
	{
        $book = Book::find($id);

        $book->title = $requestData['title'];
        $book->description = $requestData['description'];
        $book->author = $requestData['author'];
        $book->save();

        return redirect()->route('book.index');
	}

Update method have two parameters. Which passing Book id with edited value of the form.

Something to say? Tell us in comment section.