Laravel更新功能未运行正确的响应

时间:2018-12-30 17:39:35

标签: laravel laravel-routing laravel-form

当我尝试更新Laravel应用程序中的记录时,它运行的URL错误,从而导致错误404。当我在本地进行开发时,此功能运行良好,但是现在它托管在one.com服务器上,它具有停止工作。

edit.blade.php

<form method="POST" action="gins/{{ $gins->id }}">
    @method('PATCH')
    @csrf

    <div class="field">
        <label class="label" for="gin">Gin</label>
        <div class="control">
            <input type="text" class="input" name="gin"
                   placeholder="Gin" value="{{ $gins->gin }}">
        </div>
    </div>

    <div class="field">
        <label class="label" for="size">Bottle Size(ml)</label>
        <div class="control">
            <input type="text" class="input" name="size"
                   placeholder="Size (ml)" value="{{ $gins->size }}">
        </div>
    </div>

    <div class="field">
        <label class="label" for="price">Price(£)</label>
        <div class="control">
            <input type="text" class="input" name="price"
                   placeholder="Price of Gin" value="{{ $gins->price }}">
        </div>
    </div>

    <div class="field">
        <div class="control">
            <button type="submit" class="button is-success">Update Record
            </button>
        </div>
    </div>
</form>

路线

Route::patch('gins/{gin}', 'PostsController@update')->middleware('auth');
Auth::routes(); 

控制器

public function update(Request $request, $id)
{
    $gins = \App\Gins::findOrFail($id);

    $gins->gin = request('gin');
    $gins->size = request('size');
    $gins->price = request('price');

    $gins->save();

    return redirect('gins');
}

编辑页面的URL为Laravel/gins/7/edit。当我单击“提交”按钮时,它将返回URL Laravel/gins/7/gins/7,而该URL应该重定向回Laravel/gins/7

Url中的7是我尝试更新的特定记录中的记录id

1 个答案:

答案 0 :(得分:2)

像这样对URL进行硬编码始终是一个坏主意。以下

<form method="POST" action="gins/{{ $gins->id }}">
laravel/gins/之类的路由中,

的评估结果为laravel/gins/gins/7

此外,路由在动态Web应用程序中始终在变化。因此,建议您使用Named Routes。 例如:

Route::patch('gins/{gin}', 'PostsController@update')
        ->middleware('auth')
        ->name('posts.update');

,然后将表单操作更改为此:

<form method="POST" action="{{ route('posts.update', ['gin' => $gins->id]) }}">

我也会稍微清理您的update()方法。

public function update(Request $request, $id)
{
    $gins = \App\Gins::findOrFail($id);

    $gins->gin   = request('gin');
    $gins->size  = request('size');
    $gins->price = request('price');

    $gins->save();

    // change this to a named route as well        
    return redirect('gins');

    // or if you just want to return back to the previous page, you can do
    // return back(); 
}