2按钮使用Laravel访问同一路径中使用相同路径的不同方法

时间:2017-05-13 18:35:55

标签: php laravel routes parameter-passing laravel-eloquent

我的刀片中有2个按钮。我想用它们更新相同的数据库列,当我单击按钮1时,它将列更新为1,当我单击第二个按钮时它将列更新为2.我使用相同的路径来执行此操作因为我必须通过" id"从视图到控制器。

视图中的

按钮:

  {!! Form::open(['method' => 'GET', 'route' => ['show.approve_notification_application', $userdetail->id], 'style'=>'display:inline']) !!}
    {!! Form::submit('Accpet', ['class' => 'btn btn-success']) !!}
  {!! Form::close() !!}

  {!! Form::open(['method' => 'GET', 'route' => ['show.approve_notification_application', $userdetail->id], 'style'=>'display:inline']) !!}
    {!! Form::submit('Send to Super Admin', ['class' => 'btn btn-success']) !!}
  {!! Form::close() !!}

路线

Route::get('/notification_list/notification_application/{notification_id}', 'AdminController@approveNotification')->name('show.approve_notification_application');

Route::get('/notification_list/notification_application/{notification_id}', 'AdminController@sendNotificationToSuperAdmin')->name('show.approve_notification_application');

控制器

public function approveNotification($id){

        $notification = Notification::find($id);
        $notification->approved = '2';
        $notification->save();

        return redirect()->route('admin.notification_list');
    }


    public function sendNotificationToSuperAdmin($id){

        $notification = Notification::find($id);
        $notification->approved = '1';
        $notification->save();

        return redirect()->route('admin.notification_list');
    }

我不知道该怎么做。当我单击任何按钮时,只有第二个路径似乎工作,这意味着无论我单击哪个按钮,它总是将表更新为值为1.

2 个答案:

答案 0 :(得分:1)

您遇到问题的原因:

路径文件中的

- 您调用了2个具有相同名称的方法 - 这就是它到达第二条路线的原因(所选择的名称覆盖了第一条路线);

如何解决?

首先 - 删除其中一条路线。

然后 - 在表单中添加隐藏字段,以便稍后可以知道单击了哪个按钮

之后 - 你需要在你的控制器中添加一个IF - 根据$ id 像这样的东西:

if ($yourHiddenField == 1) {
   ... your code here...
} elseif ($yourHiddenField == 2 ) {
   ... your code here ...
}

(您需要先获取隐藏字段的值)

答案 1 :(得分:1)

那是因为您无法使用相同的网址和方法类型设置两条或更多条路线。您可以使用与Route:get('hi')Route::post('hi')等其他类型相同的网址。

回到你的问题,你可以这样做:

<强>按钮

 {!! Form::open(['method' => 'GET', 'route' => ['show.approve_notification_application', $userdetail->id], 'style'=>'display:inline']) !!}
{!! Form::hidden('type', 0) !!}
{!! Form::submit('Accpet', ['class' => 'btn btn-success']) !!}
{!! Form::close() !!}

{!! Form::open(['method' => 'GET', 'route' => ['show.approve_notification_application', $userdetail->id], 'style'=>'display:inline']) !!}
{!! Form::hidden('type', 1) !!}
{!! Form::submit('Send to Super Admin', ['class' => 'btn btn-success']) !!}
{!! Form::close() !!}

<强>控制器

public function approveNotification(Request $request, $id){

    $notification = Notification::find($id);
    $notification->approved = $request->input('type') == 1 ? 1 : 2;
    $notification->save();

    return redirect()->route('admin.notification_list');
}

请勿忘记在命名空间后在文件顶部插入use Illuminate\Http\Request

<强>路线

保留第一个并删除第二个。