简体   繁体   中英

single form for insert and update data

I am trying to use single form for both data insertion and data update. But I do not know how can it be done. In my form I've mentioned the action method action="{{action('BookController@create')}}" , but I want to use the same form for data insertion and data update.

//book.blade.php
<form class="form-horizontal" method="POST" action="{{action('BookController@create')}}" enctype="multipart/form-data">
  {{ csrf_field() }}
  <div class="row" style="padding-left: 1%;">
    <div class="col-md-4">
      <div class="form-group">
        <label>Book Name</label><span class="required">*</span>
        <input type="text" maxlength="100" minlength="3" autofocus="autofocus" autocomplete="off" required="required" name="NBookName" class="form-control"/>
      </div>
    </div>                        
    <div class="col-md-4">
      <div class="form-group" style="padding-left: 5%;">
        <label>Unit Price</label><span class="required">*</span>
        <input type="text" maxlength="5" required="required" autocomplete="off" runat="server" name="NBookUnitPrice"/>
      </div>                                   
      <div class="form-group" style="padding-left: 5%;">
        <button type="submit" class="btn btn-primary">Submit</button>        
      </div>                                      
    </div>
  </div>
</form>

controller code

public function edit($id)
{
  $book = Book::find($id);
  return view('pages.book',compact('book','id'));
}

route page

// for books
Route::get('/book','BookController@create');
Route::post('/book','BookController@store');
Route::get('/book/{id}','BookController@edit');

I do not know how to process it further.

I am trying to use single form for both data insertion and data update

No you don't, unless you are ready to get killed by another developer who will need to understand what you did there.

You follow the Restful Resource Controllers since Laravel 5.2

It's a quite repetetive solution template

Routes

Route::resource('book', 'BookController');

Controller

class BookController extends Controller {
    // Display list of your books
    public function index() {
        $books = Book::all();
        return view('books.index', ['books' => $books]);
    }

    // Show a form to create a book
    public function create() {
        return view('books.create');
    }

    // Show a form to edit a book
    public function edit(Book $book) {
        return view('books.edit', ['book' => $book]);
    }

    // Store a new book
    public function store(Request $request) {
        $this->validate($request, [
            'book_name' => 'required|unique:books'
        ]);

        $book = new Book();
        $book->book_name = $request->book_name;
        if($book->save()) {
            return redirect()->route('books.edit', $book)
                ->with('success', 'Successfully added a book'); // You may print this success message
        } else {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Could not add a book');      // You may print this error message
        }
    }

    // Update existing book
    public function update(Request $request, Book $book) {
        $this->validate($request, [
            'book_name' => 'required|unique:books,book_name,'.$book->getKey().',id'
        ]);

        $book->book_name = $request->book_name;
        $book->save();

        if($book->save()) {
            return redirect()->route('books.edit', $book)
                ->with('success', 'Successfully updated a book');   // You may print this success message
        } else {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Could not updated a book');      // You may print this error message
        }
    }

    // Delete existing book
    public function destroy(Book $book) {
        if($book->delete()) {
            return redirect()->back()
                ->with('success', 'Successfully deleted a book');   // You may print this success message
        } else {
            return redirect()->back()->with('error', 'Could not delete a book');      // You may print this error message
        }
    }
}

Blade

// Show all of your books using some foreach look and html table
views/books/index.blade.php

// Create a new book
views/books/index.create.php

// Edit an existing book
views/books/index.edit.php

Forms

<!-- Creating a new book (store method) -->
<form action="{{ route('books.store') }}" method="POST">
    {{ csrf_field() }}
    <input name="book_name" value="{{ old('book_name') ">
    <button type="submit">Create</button>
</form>

<!-- Updating an existing book (update method) -->
<form action="{{ route('books.update', $book) }}" method="POST">
    {{ csrf_field() }}
    {{ method_field('PUT') }}
    <input name="book_name" value="{{ old('book_name', $book->book_name) ">
    <button type="submit">Update</button>
</form>

<!-- Deleting an existing book (destroy method) -->
<form action="{{ route('books.destroy', $book) }}" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <button type="submit">Delete</button>
</form>

Didn't test the code, but still, the developer that sits next to you will not kill you for using common solution patterns.

I think you need another one route:

Route::put('/book/{id}, 'BookController@update')->name('book.update');

In your three methods you may do something like this:

public function edit($id)
{
        $action = route('book.update', ['id' => $id]);
        $book = Book::find($id);
        return view('pages.book',compact('book','id', 'action'));

}

And edit your form (i edited action and input values)

<form class="form-horizontal" method="POST" action=" 
{{ $action }}" enctype="multipart/form-data">
  {{ csrf_field() }}
  <div class="row" style="padding-left: 1%;">
<div class="col-md-4">
  <div class="form-group">
    <label>Book Name</label><span class="required">*</span>
    <input type="text" maxlength="100" minlength="3" autofocus="autofocus" autocomplete="off" required="required" value="{{ $book->name ?? '' }}" name="NBookName" class="form-control"/>
  </div>
</div>                        
<div class="col-md-4">
  <div class="form-group" style="padding-left: 5%;">
    <label>Unit Price</label><span class="required">*</span>
    <input type="text" maxlength="5" required="required" autocomplete="off" runat="server" value="{{ $book->price ?? '' }} name="NBookUnitPrice"/>
  </div>                                   
  <div class="form-group" style="padding-left: 5%;">
    <button type="submit" class="btn btn-primary">Submit</button>        
  </div>                                      
</div>

Do not merge update, create, delete, etc. methods. Another request => another method.

You are free to use one form to create and update. If you are following CRUD rules your form meethod will be POST for create and PUT for update, so place @method('PUT') inside your form body for that.

Then you need to create route Route::put('/book','BookController@update')->name('book.update'); for update and Route::post('/book','BookController@store')->name('book.store'); for store. Or just Route::resource('/book','BookController') instead all this methods. Check laravel resource doc.

Next step within your BookController create update(Request $request) method with update logic inside and store(Request $request) method with store logic.

That's it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM