简体   繁体   English

用于插入和更新数据的单一表格

[英]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. 在我的表单中,我提到了操作方法action="{{action('BookController@create')}}" ,但是我想使用相同的表单进行数据插入和数据更新。

//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 从Laravel 5.2开始,您遵循Restful资源控制器

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. 如果您遵循CRUD规则,则表单method将是POST(用于创建)和PUT(用于更新),因此请将@method('PUT')放在表单主体中。

Then you need to create route Route::put('/book','BookController@update')->name('book.update'); 然后您需要创建路由Route::put('/book','BookController@update')->name('book.update'); for update and Route::post('/book','BookController@store')->name('book.store'); 用于更新和Route::post('/book','BookController@store')->name('book.store'); for store. 为商店。 Or just Route::resource('/book','BookController') instead all this methods. 或者只是Route::resource('/book','BookController')代替所有这些方法。 Check laravel resource doc. 检查laravel资源文档。

Next step within your BookController create update(Request $request) method with update logic inside and store(Request $request) method with store logic. 你的内下一步BookController创建update(Request $request)方法里面更新逻辑和store(Request $request)方法以存储逻辑。

That's it. 而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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