我无法在laravel 5中更新该字段

时间:2018-05-28 04:22:11

标签: laravel

我的laravel代码中的Get,Post,Delete是可以的。 但我无法更新该领域。

BookController.php中的函数更新

$ data = $ this-> request-> all();

如果显示dd($ data),则为空。

是什么原因? 请帮帮我。

BookRequest.php代码:

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'name' => 'required|max:255',
            'coment' => 'required'
        ];
    }
}

BookController.php代码:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
protected $request;
protected $book;
public function __construct(Request $request, Book $book) {
    $this->request = $request;
    $this->book = $book;
}
public function update(BookRequest $request, $id) {
    $data = $this->request->all();
    $book = $this->book->find($id);
    $book->name = $data['name'];
    $book->coment = $data['coment'];
    $book->save();
    return response()->json(['status' => Response::HTTP_OK]);
}
}

3 个答案:

答案 0 :(得分:1)

如果我是你,我会像下面那样更换控制器:

because its MIME type ('text/html')

如果您已设置Route:model binding,那么您可以更好地简化Code​​。下面的代码仅适用于路径文件<?php namespace App\Http\Controllers; use App\Book; use Illuminate\Http\Response; use App\Http\Requests\BookRequest; class BookController extends Controller { public function update(BookRequest $request, $id) { $book = Book::find($id); $book->update($request->all()); return response()->json(['status' => Response::HTTP_OK]); } } 中的Route :: model设置。

查看此文档以获取更多详细信息:

https://laravel.com/docs/5.6/routing#route-model-binding

web.php

答案 1 :(得分:0)

试试这个: -

$request->all();

而不是

$this->request->all()

答案 2 :(得分:0)

我已经解决了。

我的要求:http://127.0.0.1:8000/api/book POST,key:_method:PUT

更新代码

$data = $request->all();
$book = Boook::find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();

问候。