mostafiz13 mostafiz13 - 1 year ago 57
PHP Question

call route from button click laravel

I am using the Laravel framework and the blade templating engine for one of my project, where I have a route which looks like

Route::get('/problems/{problem-id}/edit', 'AdminController@editProblem');

I have editProblem method in AdminController which returns a view

public function editProblem(Problem $problem) {
return view('admin.problem-edit', compact('problem'));

and I have a button on a view which looks like

<button class="btn btn-xs btn-info pull-right">Edit</button>

Now I want to call this route with the
when the button will be clicked. I need to pass these value to the route.

how can I do that?

Answer Source

In my opnion, you should use url() Laravel method

To call you route with the problem's id you can do:

<a href="{{ url('/problems/' . $problem->id . '/edit') }}" class="btn btn-xs btn-info pull-right">Edit</a>

I used an anchor tag, but it will be rendered like you button tag because I kept the same style class you have defined.

Why you should use url() method ?

The reason is simple, the url method will get the full url to your controller. If you don't use this, href link will get appended with current url.

For example, supose you button is located inside a given page

when someone click in your button, the result will be:{problem-id}/edit

when you would like to get this:{problem-id}/edit

Some considerations about your editProblem method

Your route has the '$id', so you need to receive this '$id' in your method

public function editProblem($problem_id) {

$problem = \App\Problem::find($problem_id); //If you have your model 'Problem' located in your App folder

return view('admin.problem-edit', compact('problem'));