Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call route from button click laravel

I am using the Laravel framework and the blade templating engine for one of my projects, 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 $problem->id when the button will be clicked. I need to pass these value on the route.

how can I do that?

like image 364
rimonmostafiz Avatar asked Aug 02 '16 00:08

rimonmostafiz


2 Answers

Try This:

<button type="button" onclick="window.location='{{ url("users/index") }}'">Button</button>

Little Suggestion: When you're defining routes in laravel give it a unique name, it helps you to keep track on each url like this

Route::get('/problems/{problem-id}/edit', 'AdminController@editProblem')->name('showProblemEditPage');
Route::post('/problems/{problem-id}/edit', 'AdminController@updateProblem')->name('updateProblem');

Now you use this route in blade with just name for post and get both

Exmaple of GET route :

<button type="button" onclick="window.location='{{ route("showProblemEditPage",[$problemIdParameter]) }}'">Button</button>

OR

<a href="{{ route("showProblemEditPage",[$problemIdParameter]) }}">Button</button>

OR

<button type="button redirectToUrl" data-redirect-url="{{ route("showProblemEditPage",[$problemIdParameter]) }}">Button</button>
<script>
  $(document).on('click','.redirectToUrl',function(){
    let getRedirectUrl = $(this).attr('data-redirect-url');
    window.location.href= getRedirectUrl;
  });
</script>

Example of POST route :

In case if you are submiting form via submit button click

<form action={{ route('updateProblem',[$problemIdParameter]) }}>
  .....

  <button type="submit">Submit</button>
</form>

In case if you are submiting form via ajax on button click

<form action={{ route('updateProblem',[$problemIdParameter]) }}>
  .....

  <button type="button" class="submitForm" >Submit</button>
</form>
<script>
   $(document).on('click','.submitForm',function(){
      let getForm = $(this).parents('form');
      let getFormActionUrl = getForm.attr('action');
      $.ajax({
          url: getFormActionUrl,
          .....
          .....
          .....
          .....
          .....
      });
   });
</script>
like image 196
Vipertecpro Avatar answered Sep 22 '22 10:09

Vipertecpro


Was asked for route inquiry. so that :

<button  onclick="window.location='{{ route("some_route_name") }}'"...>
</button>

in web.php

Route::get('/some_route_url', [SomeRouteController::class,'some_func'])->name('some_route_name');
like image 36
CodeToLife Avatar answered Sep 22 '22 10:09

CodeToLife