如何解决laravel 5.3中App \ Http \ Controllers \ UserController :: destroy()的缺失参数2?

时间:2016-12-17 21:43:13

标签: php laravel get routes laravel-5.3

我的观点是这样的:

@foreach($users as $user)
    <tr>
        <td>{!! $user->id !!}</td>
        <td>{!! $user->username !!}</td>
        <td>{!! $user->phone !!}</td>
        <td>{!! $user->address !!}</td>
        <td>
            {!! Form::open(['route' => ['users.destroy', $user->id], 'method' => 'delete']) !!}
            <div class='btn-group'>
                <a href="{!! route('users.edit', [$user->id]) !!}" class='btn btn-default btn-xs'><i class="glyphicon glyphicon-edit"></i></a>
                {!! Form::button('<i class="glyphicon glyphicon-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure?')"]) !!}
            </div>
            {!! Form::close() !!}
        </td>
    </tr>
@endforeach

我的路线\ web.php是这样的:

Route::get('users/destroy/{year}', 'UserController@destroy')->name('users.destroy.year');

Route::resource('users', 'UserController');

我的控制器是这样的:

public function destroy($id, $year)
{
    $user = $this->userRepository->findWithoutFail($id);

    if (empty($user)) {
        Flash::error('User not found');

        return redirect(route('users.index'));
    }

    $this->userRepository->delete($id);

    Flash::success('User deleted successfully.');

    // return redirect(route('users.index'));
    return redirect(route('users.index.year', ['year' => $year]));
}

存在这样的错误:

ErrorException in UserController.php line 205: Missing argument 2 for App\Http\Controllers\UserController::destroy()

网址如下:http://localhost/mysystem/public/users/10

点击按钮删除后,我希望网址如下所示:http://localhost/mysystem/public/users/index/2020

有没有人可以帮助我?

3 个答案:

答案 0 :(得分:0)

试试这个

$year = 2020;
{!! Form::open(['route' => ['users.destroy', $user->id, $year], 'method' => 'delete']) !!}

答案 1 :(得分:0)

也许你可以试试: 在routes / web.php中,只需声明路由资源

Route::resource('users', 'UserController');

在您的表单中添加隐藏年份值的输入

{!! Form::open(['route' => ['users.destroy', $user->id], 'method' => 'delete']) !!}


<input type="hidden" name="year" value="2020">

然后像那样更新你的控制器

public function destroy(Request $request, $id)
{
$user = $this->userRepository->findWithoutFail($id);
$year = $request->year;
if (empty($user)) {
    Flash::error('User not found');

    return redirect(route('users.index'));
}

$this->userRepository->delete($id);

Flash::success('User deleted successfully.');

// return redirect(route('users.index'));
return redirect('users/index/'.$year);

}

答案 2 :(得分:0)

您在open方法中使用了错误的路线名称,它应该是users.destroy.year

因此,您的表单将显示为:

{!! Form::open(['route' => ['users.destroy.year', $user->id, $year], 'method' => 'delete']) !!}