Laravel: Passing Variable / Parameter from blade.php View to a function in controller via Route

43 views Asked by At

I'm trying to pass a loop iterator variable $user from my view's Datatable (on clicking edit button) to a controller function using a Route.

My Route in web.php:

Route::get('/add_all',[AddPersInfoController::class,'add_all'])->name('add_all');

My Controller function:

public  function add_all($user_id){ 
...
}

Datatable code in draft.blade.php View:

 @php $i=1 @endphp
                      @foreach($pers as $user)
                      <tr>
                        <td>{{$i}}</td>
                        <td>{{$user->user_type ?? 'N/A'}}</td>
                        <td>{{$user->rank->name ?? 'N/A'}}</td>
                        <td>{{$user->name ?? 'N/A'}}</td>
                        <td><a href="{{route('add_all',[$user->id])}}"><button class="btn btn-icon btn-primary">  <i class="demo-pli-pencil fs-5"></i> </button> </a></td>
                      </tr> 
                      @php $i++; @endphp
                      @endforeach

Where the $pers variable is sent to this view via another route using compact() function.

I have tried passing specific var like [$user->id] and a different syntax like $user but nothing works. All of these give the same error.

Too few arguments to function App\Http\Controllers\AddPersInfoController::add_all(), 0 passed

There are other answers who try to suggest using URL::to instead of href. But I want a solution using href only.

What am I doing wrong?

1

There are 1 answers

1
Karl Hill On BEST ANSWER

Your route definition does not expect any parameters. You need to define a parameter in your route definition in web.php file.

Route::get('/add_all/{user}', [AddPersInfoController::class,'add_all'])->name('add_all');

In the above code, {user} is a placeholder for the parameter that you want to pass to the add_all method in your AddPersInfoController. Now, your add_all method in the AddPersInfoController should be able to receive the $user parameter.

public function add_all($user) { 
    // ...
}

And in your blade file, you can pass the $user->id as a parameter to the route.

<a href="{{ route('add_all', ['user' => $user->id]) }}">
    <button class="btn btn-icon btn-primary">
        <i class="demo-pli-pencil fs-5"></i>
    </button>
</a>