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

时间:2018-08-03 07:18:04

标签: php laravel laravel-5

我正在尝试使用单一形式进行数据插入和数据更新。但是我不知道该怎么办。 在我的表单中,我提到了操作方法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>

控制器代码

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

路线页面

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

我不知道如何进一步处理。

4 个答案:

答案 0 :(得分:3)

  

我正在尝试使用单一形式进行数据插入和数据更新

不,您不会,除非您准备被另一名需要了解您在那做过什么的开发人员杀死。

自Laravel 5.2起,您遵循Restful Resource Controllers

这是一个重复性很强的解决方案模板

路线

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

控制器

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
        }
    }
}

刀片

// 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

表格

<!-- 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>

虽然没有测试代码,但是,坐在您旁边的开发人员仍然不会因为使用常见的解决方案模式而丧命。

答案 1 :(得分:1)

我认为您需要另一条路线:

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

在三种方法中,您可以执行以下操作:

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

}

并编辑您的表单(我已编辑动作和输入值)

<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>

答案 2 :(得分:1)

请勿合并更新,创建,删除等方法。另一个请求=>另一个方法。

您可以自由使用一种表单来创建和更新。如果您遵循CRUD规则,则表单method将是POST(用于创建)和PUT(用于更新),因此请将@method('PUT')放在表单正文中。

然后,您需要创建路由Route::put('/book','BookController@update')->name('book.update');进行更新,并创建Route::post('/book','BookController@store')->name('book.store');进行存储。或者只是Route::resource('/book','BookController')而不是所有这些方法。查看laravel资源文档。

BookController中创建带有内部更新逻辑的update(Request $request)方法和具有存储逻辑的store(Request $request)方法的下一步。

就是这样。

答案 3 :(得分:0)

首先,将这些输入和按钮放在您的模态中:

<input type="hidden" name="id" id="id" value="" /> 
<input type="hidden" name="button_action" id="button_action value="insert" /> 
<input type="submit" name="action" id="action" class="btn btn-success" value="submit" /> 
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

对于更新,通过 jquery 为您的 id 输入提供一个 id:

$('#id').val(id); 
$('#button_action').val('update'); 
$('#action').val('update'); 

然后在您的控制器中:

if($request->get('button_action') == "insert") {  
    $success_output = insert 
} 
if($request->get('button_action') == "update") {  
    $success_output = update 
}