Home > Mobile >  Prompting a confirmation dialog before redirecting to a route from within the controller
Prompting a confirmation dialog before redirecting to a route from within the controller

Time:01-03

In one of my project's view, I have a table with id="users-list" in which one of its column will fetch the $action values returned from the index_datatables function in the UserController.

UserController.php

    .
    .
    .

    public function index_datatables(Request $request){

        $orderColumnDirection = $request->input('order.0.dir');
        $orderColumnIndex = $request->input('order.0.column');
        $orderColumnName = $request->input("columns.{$orderColumnIndex}.data");
        $rows = $q->orderBy($orderColumnName, $orderColumnDirection)->get();
        $data = [];

        foreach ($rows as $row){
            $action = 
                '<div  role="group" aria-label="action example">
                    <a href="'. route('user.edit', [$row->id]) .
                            '" >Update
                    </a>
                    <a href="'. route('user.delete', [$row->id]) .
                            '" >Delete
                    </a>
                </div>';
            $data[] = array('id' => $row->id, 'action' => $action);
        }

        $json_data = array("data"=> $data);
        return json_encode($json_data);
    }

    public function edit($id){
        . . .
    }

    public function delete($id){

        // Need to prompt some sort of "Cancel/Proceed" dialog here

        $user = User::findOrFail($id)->delete();        
        return redirect()->back()->with('message','User deleted successfully');
    }

    .
    .
    .

web.php

.
.
.

Route::prefix('user')->group(function(){
    Route::get('/{id}/save', 'UserController@edit')->name('user.edit');
    Route::get('/{id}/delete', 'UserController@delete')->name('user.delete');
}

.
.
.

I want to alert the user with some 'OK or Cancel' dialog on Delete action.

I tried with this line

\Session::flash('message','Are you sure');

but that would only be flashed when the view is reloaded (redirected).

So, I would like to ask how do I call a such popup in view from within the controller (before redirecting)?

CodePudding user response:

You could just use plain javascript for a confirm dialog. Or use javascript libraries for some prettier dialogues (bootbox, swal2).

foreach ($rows as $row){
    $action = 
        '<div  role="group" aria-label="action example">
            <a href="'. route('user.edit', [$row->id]) .
                    '" >Update
            </a>
            <a href="'. route('user.delete', [$row->id]) .
                     '"  onclick="confirm(\'are you sure?\')">Delete
            </a>
        </div>';
    $data[] = array('id' => $row->id, 'action' => $action);
}
  • Related