Call route from button click laravel - php

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?

In my opnion, you should use url() Laravel method
To call you route with the problem's id you can do:
Edit
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
yourdomain.com/a-given-page/
when someone click in your button, the result will be:
yourdomain.com/a-given-page/problems/{problem-id}/edit
when you would like to get this:
yourdomain.com/problems/{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'));
}

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>

You will need to create a link to this route:
Edit
If you use named routes, this will be even easier:
Route::get('/problems/{problem-id}/edit', ['as' => 'problems.edit', 'uses' => 'AdminController#editProblem']);
And then you just need to call the route method:
Edit

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');

I used the following code and it worked.
<button class="btn border button" id="go-back-btn" onclick="window.location='{!! route('getDashboardScreen') !!}?MilkCompanyID={!!session('MilkCompanyID')!!}'">Go back</button>

Related

Data does not send to controller

I have a project of an online forum with Laravel 8, and in this project, I have a "Like" button at Blade like this:
<form action="{{ route('questions.likes', $show->id) }}" method="POST">
#csrf
<button class="btn">
<i class="fas fa-thumbs-up"></i>
</button>
</form>
$show->id is the question id
And here is the route questions.likes:
Route::post('questions/{id}/thumbsUp' , [LikeController::class, 'store'])->name('questions.likes');
And then I called the Controller LikeController with the store method which goes like this:
public function store(Request $request, Question $id)
{
dd('output')
}
But now the problem is it does not send data to this method, I mean when you click the button nothing happens at all!
So what is going wrong here?
If you would like to take a look at all the routes in the web.php file, here it is.
You will have to change store(Request $request, Question $id) to store(Request $request, Question $question). Laravel will automatically resolve the provide $show->id argument to the Question model if you use the following route:
Route::post('questions/{question}/thumbsUp' , [LikeController::class, 'store'])->name('questions.likes');
<button type="submit" value="Submit">Submit</button>
Set a type for your button, check if it works or not

Trying to submit one <form> with method="POST" duplicates the route and doesn't save the information with an store function()

Im trying to submit one form with method post to save one element in astore function() but when I click submit duplicates the route, for example looking like this:entradas/1/ventaEntrada/200000/montoTotal/entradas/1/ventaEntrada/200000/montoTotal and doesn't save the information, I dont know why this is happening
Below i will let the code of my route,my form,my create function() and my store function()
Also show404 Not Found when I click submit
Route
Route::resource('/entradas/{id_entrada}/ventaEntrada/{precio_entrada}/montoTotal', 'Venta_entradaController');
create function()
public function create(Request $request,$id_entrada,$precio_entrada){
$venta_entrada = DB::select(DB::raw(
"SELECT monto_total,fecha,fk_cliente_natural,fk_cliente_juridico
FROM venta_entrada "
)
);
return view('home.crearVenta_entrada')
->with('venta_entrada',$venta_entrada)
->with('id_entrada',$id_entrada)->with('precio_entrada',$precio_entrada);
}
store function()
public function store(Request $request,$id_entrada,$precio_entrada)
{
$venta_entrada=new Venta_entrada();
$venta_entrada->monto_total=$precio_entrada+$request->monto_total;
$now = new \DateTime();
$venta_entrada->fecha=$now->format('d-m-Y');
$venta_entrada->fk_cliente_natural=1;
$venta_entrada->save();
return back();
}
Form with the method POST
<form action="entradas/{{$id_entrada}}/ventaEntrada/{{$precio_entrada}}/montoTotal" method="POST">
#csrf
<input type="number" name="monto_total" placeholder="Monto total" class="form-control mb-2" required>
<button clas="btn btn-primary btn-block" type="submit">ADD</button>
BACK
</form>
I have check your problem and you have use "Resource Route" right.
so for routing run following command in your terminal/command prompt
php artisan route:list
It will show all routes lists and find your action name
Then you'll add in form action name like
<form action="{{ route('name') }}" method="post">
...
</form>
Example:
<form action="{{ route('Venta_entrada.store') }}" method="post">
...
</form>
I hope it will help you :)

Php laravel 5.3 passing an input value from one blade file to another blade file

I want to pass an input value from one blade file to another blade file.
I'm new to PHP Laravel, and I'm getting an error when attempting to use it.
I think my syntax is wrong here. Can somebody help?
channeling.blade:
<select class="form-control " name="fee" id ="fee"></select>
This is the link to the next page, where i want to send the value of "fee":
<input type="hidden" value="fee" name="fee" />
Click to Channel</p>
This is my web.php:
Route::post('pay', [
'as' => 'fee',
'uses' => 'channelController#displayForm'
]);
This my controller class:
public function displayForm()
{
$input = Input::get();
$fee = $input['fee'];
return view('pay', ['fee' => $fee]);
}
Error message:
Undefined variable: fee
(View: C:\xampp\htdocs\lara_test\resources\views\pay.blade.php)
pay.blade:
<h4>Your Channeling Fee Rs:"{{$fee}}"</h4>
You should use form to send post request, since a href will send get. So, remove the link and use form. If you use Laravel Collective, you can do this:
{!! Form::open(['url' => 'pay']) !!}
{!! Form::hidden('fee', 'fee') !!}
{!! Form::submit() !!}
{!! Form::close() !!}
You can value inside a controller or a view with request()->fee.
Or you can do this:
public function displayForm(Request $request)
{
return view('pay', ['fee' => $request->fee]);
}
I think you can try this, You mistaken url('pay ') with blank:
change your code:
Click to Channel</p>
to
Click to Channel</p>
Further your question require more correction so I think you need to review it first.
You can review about how to build a form with laravel 5.3. Hope this helps you.
You have to use form to post data and then you have to submit the form on click event
<form id="form" action="{{ url('pay') }}" method="POST" style="display: none;">
{{ csrf_field() }}
<input type="hidden" value="fee" name="fee" />
</form>
On the click event of <a>
<a href="{{ url('/pay') }}" onclick="event.preventDefault();
document.getElementById('form').submit();">
Logout
</a>
tl;dr: I believe #AlexeyMezenin's answer is the best help, so far.
Your current issues:
If you have decided to use Click to Channel, you should use Route::get(...). Use Route::post(...) for requests submitted by Forms.
There isn't an Input instance created. Input::get() needs a Form request to exist. Thus, the $fee an Undefined variable error message.
The value of <input type="hidden" value="fee" name="fee"/> is always going to be the string "fee". (Unless there's some magical spell casted by some JavaScript code).
The laravel docs suggest that you type-hint the Request class when accessing HTTP requests, so that the incoming request is automatically injected into your controller method. Now you can $request->fee. Awesome, right?
The way forward:
The BasicTaskList Laravel 5.2 tutorial kick-started my Laravel journey.
I changed the code like this and it worked..
echanneling.blade
<input type="hidden" value="fee" name="fee" />
<button type="submit" class="btn btn-submit">Submit</button>
channelController.php
public function about(Request $request)
{
$input = Input::get();
$fee = $input['fee'];
return view('pay')->with('fee',$fee);
}
Web.php
Route::post('/pay', 'channelController#about' );

Passing variable from button to controller Laravel

I am having a little routing problem in Laravel 5.2. I have a result page which shows detailed information about personnel. I would like a button, which when enabled, generates a PDF page. Passing the variables has been a problem but I am very close now! I will public my code to elaborate.
result page
<form action="generatePDFpage" method="get">
<button type="submit" class="btn btn-default">Generate PDF!</button>
</form>
routes.php
Route::get('/dashboard/result/generatePDFpage', 'resultController#GeneratePDFc');
GeneratePDFc controller
public function GeneratePDFc(){
$id_array_implode = "HALLO";
$pdf= PDF::loadView('GeneratePDF', ["test"=>$id_array_implode])->setPaper('a4', 'landscape');
return $pdf->stream('invoice.pdf');
}
So, on the result page I am using a array ($id_array) to search the database for the matching records. I need to pass this variable onto the GeneratePDFc controller, so that I can pass that again to the loadView function!
Could someone please help me out? :-)
When you're using get method, you can do just this:
<a href="{{ route('route.name', $parameter) }}">
<button type="submit" class="btn btn-default">Generate PDF!</button>
</a>
For other methods you can use something like this (this one is for DELETE method):
<form method="POST" action="{{ route('route.name', $parameter) }}" accept-charset="UTF-8">
<input name="_method" type="hidden" value="DELETE">
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-default">Generate PDF!</button>
<input type="hidden" value="someVariable" />
</form>
To get variable, use something like this:
public function generatePDF(Request $request)
{
$someVariable = $request->someVariable;
I don't know Laravel but I think when in your action="" of the form you can put your route with its parameters no ?
I've found it here : https://laravel.com/docs/4.2/html#opening-a-form
And access the variable in your controller using the $request var

Laravel form include input in action attribute

LARAVEL 5.0
PHP 5.4.45
I have a route that is shaped like this :
/app/Http/routes.php
Route::get('/clients/search/{id}', 'ClientController#searchById')->where('id', '[0-9]+');
Route::get('/clients/search/{text}', 'ClientController#searchByText')->where('text', '[a-zA-Z]');
I will not print my view here but it simply search for the exact client (case id) or the first 10 clients (case text).
Then I want to create a search form. I created the route :
/app/Http/routes.php
// Route::get('/clients/search/{id}', 'ClientController#searchById')->where('id', '[0-9]+');
// Route::get('/clients/search/{text}', 'ClientController#searchByText')->where('text', '[a-zA-Z]');
Route::get( '/clients/search', 'ClientController#search');
The controller for this route :
/app/Http/Controllers/ClientController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class ClientController extends Controller {
// Controllers for the 'searchById' and 'searchByText'
public function search() {
return view('client.search.search', [
'title' => 'Client search form',
'title_sub' => ''
]);
}
}
And the view for this search form :
/ressources/view/client/search/search.blade.php
<form action="/clients/search/INPUT HERE ?" method="get">
<div class="input-group">
<input id="newpassword" class="form-control" type="text" name="password" placeholder="Id de client, nom, prénom, ...">
<span class="input-group-btn">
<button id="button_search" class="btn green-haze" type="submit"><i class="fa fa-search fa-fw"></i></button>
</span>
</div>
</form>
QUESTION
How can I, before submit, pass an input as a part of my action attribute for my form ? The point is to be able to launch those kind of requests :
/clients/search/26
/clients/search/Mike%20%Folley
/clients/search/Paris
So my controllers handling this route could do the job. Is there any way to do that ? Or should I go for JavaScript solution (which make me sad a bit) ?
Yes, you need javascript to modify request URL before it is even sent :). No form tag needed for that, vanilla js approach like this might be sufficient:
<input type="text" id="search">
<button onclick="search()">
Submit
</button>
<script>
function search() {
window.location='/search/' +
encodeURIComponent(document.getElementById('search').value);
}
</script>
You can and should just use one route and then in controller's method decide on what to search and what view to return. Routes should contain the least amount of logic possible.

Categories