I create form in Laravel:
<form action="/redeem" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="key" class="form-control" placeholder="ENTER VOUCHER CODE">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
and now when I try to submit that I get:
http://localhost:8888/redeem?key=NBtGJ5pZls&search=
but I need to get just:
http://localhost:8888/redeem/NBtGJ5pZls
also in route I have:
Route::get('/redeem/{key}', 'OrdersController#redeem');
How to get redirected to redeem/NBtGJ5pZls with my form?
Change your route to:
Route::post('/redeem', 'OrdersController#redeem');
And then get key in controller:
public function redeem(Request $request)
{
$key = $request->key;
And finally, change your form:
<form action="/redeem" method="post" class="sidebar-form">
{{ csrf_field() }}
You've got 2 options:
The first is let your frontend code be the way it is, update the route, and work with the GET parameter.
The second one is using some javascript to rewrite the URL you want to access.
For example this (it's using jQuery):
$('#search-btn').click(function() {
var key = $('input[name=key]').val();
window.location.href = '/redeem/' + key;
});
I prefer the first one, because javascript can be modified by the end-user.
Related
I am having a problem with the routing.
Firstly, I am on the page (rate product)/{$id}
Next, when clicking the button, I want to go to another view (addReview/{$productID}/{$clientID}) But it gives me an error.
-web.php file
Route::get('rateProduct/{id}', 'CatalogController#getProduct')
->name('rateProduct');
Route::post('./addReview/{$productID}/{$clientID}','ReviewController#addReview')
->name('rateProduct.addReview');
add_review.blade.php
<div class="mb-3">
<form method="post" action="{{url('rateProduct.addReview', [$product->id, 10]) }} value="{{ csrf_token() }}"">
{{--{{ csrf_field() }}--}}
<label for="exampleFormControlTextarea1" class="form-label">Share your thoughts!</label>
<textarea class="form-control rounded" id="exampleFormControlTextarea1" rows="3"
placeholder="Tell us about your experiecnce in a couple of sentences" name="comment"></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
ReviewController.php
class ReviewController extends Controller
{
public function addReview($productID, $clientID)
{
if(isset( $_POST['submit'])) {
$comment = $_POST["comment"];
}
$date = date_create();
$reviewID = DB::table('review')->max('id') + 1;
$data = array(
'id'=>$reviewID,
"comment"=>$comment,
"review_date"=>date_timestamp_get($date),
"rating"=>1,
"client_id"=>$clientID
);
DB::table('review')->insert($data);
$data2 = array('product_id'=>$productID,"review_id"=>$reviewID);
DB::table('product_review')->insert($data2);
return view('pages/product-page');
}
}
Review model
class Review extends Model
{
use HasFactory;
public $timestamps = false;
protected $table = 'Review';
public function owner() {
return $this->belongsTo('App\Models\Product');
}
}
You have error in routing .Remove dot from the beginning(./addReview/{$productID}/{$clientID}) of string in post method.
Route::post('addReview/{$productID}/{$clientID}','ReviewController#addReview')->name('rateProduct.addReview');
Also you are using url method for named routing in form action it should be
<form method="post" action="{{route('rateProduct.addReview', [$product->id, 10]) }}" >
#csrf
Firstly you have a random . at the start of your route and $ symbols in your parameters, they needs to go.
Route::post('/addReview/{productID}/{clientID}','ReviewController#addReview')
->name('rateProduct.addReview');
Next you need to fix the invalid markup of your add_review blade file, you have mismatched opening/closing elements. You are also using a named route but using the url helper which works with paths rather than route names. You also want to add back in the #csrf token back in otherwise you'll get a 419 error.
<div class="mb-3">
<form method="post"
action="{{ route('rateProduct.addReview', [$product->id, 10]) }}">
#csrf
<label for="exampleFormControlTextarea1" class="form-label">
Share your thoughts!
</label>
<textarea class="form-control rounded"
id="exampleFormControlTextarea1"
rows="3"
placeholder="Tell us about your experiecnce in a couple of sentences"
name="comment">
</textarea>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
You can see a working example here.
I'm developing a web application, and I want to pass variable called ID when the form method is post that linked to open other form but in the config/routes I'm using $routes[page_A][get] = 'Controller' not $routes[page_A][post] = 'Controller'.
I'm using Codeigniter framework here, I've tried to change the controller with $this->input->get('id') but it doesn't work and I don't have any idea whats really happen in my codes.
The Sender Form View code
<form action="<?= base_url().'progres_save'; ?>" method="POST">
<div class="form-group">
<div class="form-row">
<label for="idJobOrder">ID Job Order</label>
<input type="text" name="idJobOrder" class="form-control" value="<?php echo $rd[0]->kodejobglobal; ?>" readonly>
</div>
</div>
<div class="form-group">
<div class="form-row">
<a class="btn btn-primary col-xl-1 col-sm-1 mb-1 ml-auto mr-0 mr-md-2 my-0 my-md-3" href="job" id="back" role="button"><i class="fas fa-fw fa-arrow-left"></i> Back</a>
<button class="btn btn-primary btn-block col-xl-1 col-sm-1 mb-1 mr-0 mr-md-2 my-0 my-md-3">Save <i class="fa fa-fw fa-arrow-right"></i></button>
<input type="hidden" name="id" value="<?php echo $rd[0]->kodejobspesifik ?>">
</div>
</div>
</form>
The Sender Form Controller code
public function save()
{
$idglobal = $this->input->post('idJobOrder');
$data = array('jobnya' => $idglobal );
$this->Model_joborder->save_pg($data,'lapharian');
redirect('progres_material');
}
The Config Routes code
$route['progres_save']['get']='error';
$route['progres_save']['post']='save';
$route['progres_material']['get']='matused';
$route['progres_material']['post']='error';
The Recipient Form Controller code
public function matused()
{
$id = $this->input->get('id');
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
The Recipient Form View code
<form method="POST" action="<?= base_url().'matsave'; ?>">
<div class="form-group">
<div class="form-row">
<?php if (isset($rd[0])) {?>
<input type="hidden" value="<?php echo $rd[0]->jobspesifiknya; ?>" name="idClient" class="form-control" placeholder="First name" readonly>
<?php } ?>
</div>
</div>
</form>
What I expect is the input id value from Sender will be passed and catch on Recipient form as input idClient. Can anyone her help me to find out the solution? Thank you.
You can use PHP global variable $_REQUEST to capture the data if you are not sure about the request type like this,
public function matused()
{
$id = $_REQUEST['id'];
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
You forgot to include the id data on the redirect after the save() method is called, so you will not get anything by calling $this->input->get('id').
To solve this, pass the id data along with the redirect :
redirect('progres_material?id=' . $this->input->post('id'));
But that of course it will gives you an extra parameter on the url. If you don't want additional parameter, you could alternatively use session to pass id data while redirecting, on CodeIgniter there is a method called set_flashdata to do this :
$this->session->set_flashdata('id', $this->input->post('id'));
redirect('progres_material');
And to get the id session data on the matused() method, use the following code :
$id = !empty($this->session->flashdata('id')) ? $this->session->flashdata('id') : $this->input->get('id');
I want To Store the current user $emp->id from href , and use in the input value as like in my code that is written below. Is is possible? or if possible then please help me? and if this Question is not a big problem so i am sorry for that in advance.
<a href="{{'/employee'}}?id={{$emp->id}}" type="button" name="user_id" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Apply Attribute
</a>
<form action="{{'/rating'}}" method="post">
{{csrf_field()}}
<input type="hidden" name="user_id" value="{{store here current user}}">
</form>
Seems you just need paste your current user inside INPUT:
<form action="{{'/rating'}}" method="post">
{{csrf_field()}}
<input type="hidden" name="user_id" value="{{ $emp->id }}">
</form>
.....
If you want to use an id from a url you can :
Route::get('/url/{emp}', 'YourController#method');
In your controller:
public function method(Employee $emp) {
//Your code
return view('youre.view', compact('emp'))
}
Now in your view you have $emp and can acces id like $emp->id.
Offcourse name it what you want but be sure to name it the same in your route,controller and view.
Now you don't need a forEach loop, because of the binding you already have the employee from the url
p.s: Employee model is just an assumption..name it whatever your model is called.
You can use route function in blade for this.
Try this on web.php :
Route::get('/employee/{id}', 'YourController#YourMethod')->name('routename');
on your Controller your method need to have an arguments
public function YourMethod($id){
// Code here
}
And on your blade make your href with route
Link
Href Like That:
<a href="{{$emp->id}}" type="button" id="uu_id" class="btn btn-primary uu"
data-toggle="modal" data-target="#myModal"> Apply Attribute </a>
Using This Script To get Value from Href:
<script type="text/javascript">
$(document).ready(function() {
$(".uu").click(function(event) {
var u_id = $(this).attr('href');
event.preventDefault();
document.getElementById("hiddenVal").value = u_id;
});
});
</script>
And in your Form like this:
<form action="{{'/rating'}}" method="post">
{{csrf_field()}}
<input type="submit" style="margin-bottom: 10px;" class="btn btn-success
pull-right" name="apply" value="Apply"/>
<input type="hidden" name="hiddenVal" id="hiddenVal" />
</form>
And Last How to get this Value in the Controller And save to Database:
public function store(Request $request)
{
$rates = new Rating;
$user_id = $_POST['hiddenVal'];
$rates->user_id = $user_id;
$rates->save();
return redirect('/employee');
}
I am working on a Laravel 5.4 application in which I want to enable the user to delete certain images which they have uploaded. The images have a small x on the right top which makes a modal pop up. I added a partial code of the modal form. When I want to submit the destroy option I get the error:
(1/1) MethodNotAllowedHttpException
in RouteCollection.php (line 251)
Could someone help me explain what I am doing wrong. I have tried changing the method in the form to DELETE and changed the route file to get, post, any etc.
Modal popup:
<a data-toggle="modal" data-target="#destroyModel" data-route="{{ route('client.progress.destroy', [$progressPicture]) }}" data-name="{{ $progressPicture->original_file }}" data-value="{{ $progressPicture->id }}">
<span class="close">×</span>
</a>
Modal form:
<form method="POST" action="#" accept-charset="UTF-8">
<input name="_method" type="hidden" value="delete">
<input type="hidden" name="_token" value="ud9UPrV3tXJ0iuQ96TELClQUcTksKx3Bimv54h9Z">
<input name="id" type="hidden" value="">
<button type="button" class="btn btn-default" data-dismiss="modal">Annuleren</button>
<button type="submit" class="btn btn-danger"><i class="fa fa-lg fa-trash"></i> Verwijderen</button>
</form>
Route file
Route::post('destroy_progress', 'Client\PictureController#destroyProgress')->name('progress.destroy');
JS
<script type="text/javascript">
$(document).ready(function () {
$('#destroyModel').on('show.bs.modal', function (event) {
let button = $(event.relatedTarget);// Button that triggered the modal
let modal = $(this);
let original_file = button.data('original_file');
let title = ":original_file verwijderen?";
title = title.replace(":original_file", original_file);
let message = "Weet u heel zeker dat u :original_file wilt verwijderen?";
message = message.replace(":original_file", name);
modal.find('.modal-footer form').attr('action', button.data('route'));
modal.find('.modal-title').html(title);
modal.find('.modal-body').html(message);
modal.find('.modal-footer input[name=id]').val(button.data('id'));
});
});
</script>
HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
To generate the hidden input field _method, you may also use the method_field helper function:
<?php echo method_field('PUT'); ?>
You can also do it using laravel blade template as
{{ method_field('PUT') }}
Then create a route which accepts the PUT request as
Route::put('destroy_progress', 'Client\PictureController#destroyProgress')->name('progress.destroy');
may I suggest using Laravel Forms
here is the link https://laravelcollective.com/docs/5.4/html but instead of using composer require "laravelcollective/html":"^5.4.0" just use this composer require "laravelcollective/html" to get the latest version, because the latest version solved the syntactical errors, the most common was the token() method
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