clean url generate GET method laravel - php

When i submit a GET method form url generate like :
example.com/machine?brand=xx&model=2016&color=red&km=110
But i want to generate url like :
example.com/machine/xx/2016/red/km=110
My Route :
Route::get('/machine/{brand}/{model}/{color}/{km}',['as'=>'machine.search','uses'=>'searchController#searchmachine']);
Form :
{!! Form::open(['route'=>'machine.search','method'=>'GET','class'=>'form-horizontal','role'=>'form']) !!}

You will have to do it in JS. Here is the form
<form action="machine">
<input name="brand"/>
<input name="model"/>
<input name="color"/>
<input name="km"/>
<button type="submit" onclick="window.location.href=this.form.action + this.form.brand.value + this.form.model.value + this.form.color.value + this.form.km.value;">
Submit
</button>
</form>
The submit button will generate the url
http://website.com/machine/brandvalue/modelvalue/colorvalue/kmvalue
In your case, you readapt your form by replacing route by url because using route would require you to pass parameters
{!! Form::open(['url'=>'machine','method'=>'GET','class'=>'form-horizontal','role'=>'form']) !!}

You are not using a good practice for doing your search, at first your route must look like this:
Route::get('/machine/search',['as'=>'machine.search','uses'=>'searchController#searchmachine']);
Then in your searchController:
class searchController extends Controller {
public function searchmachine(Request $request)
{
$brand = $request->brand;
$model = $request->model;
$km = $request->km;
$color = $request->color;
//Do your things.
}
}
And this should work:
example.com/machine/search?brand=xx&model=2016&color=red&km=110

Related

Symfony form rendered in twig template as controller is not submitting

I'd like to have simple "Search" input field in base.html.twig. Normally I would need to write code to maintain form in every route. To solve this problem I decided to create separate controller with route to render it directly in base.html.twig template:
<div class="top-middle col-12 col-md-6 d-flex order-2 order-md-1">
{{ render(controller("App\\Controller\\SearchController::searchProduct"))}}
</div>
It works find except nothing happens when the form is submitted. I tried it in normal way in one of my routes and it was working fine. So don't know where the problem is.
My SearchController with route which is rendered in twig :
class SearchController extends AbstractController
{
#[Route('search-product', name: 'search_product')]
public function searchProduct(Request $request)
{
$searchForm = $this->createForm(SearchProductType::class);
$searchForm->handleRequest($request);
if ($searchForm->isSubmitted() && $searchForm->isValid()) {
dump('Form submitted');
}
return $this->render('components/search-input.html.twig', [
'searchForm' => $searchForm->createView()
]);
}
}
Search input.html.twig component:
<div class="top-search">
<i class="bi-search top-search__icon"></i>
{{ form(searchForm) }}
</div>
and the main controller which renders index.html.twig with base.html.twig:
#[Route('/', name: 'home')]
public function index(FileHandler $fileHandler, SessionInterface $session, Request $request): Response
{
$products = $this->doctrine->getRepository(Product::class)->getProducts('Dresses', 4);
$products = $this->addPathToImages($products, 'Dresses');
return $this->render('shop/index.html.twig', [
'products' => $products
]);
}
The line
dump('Form submitted');
is not executed when the form is submitted. Page refreshes but nothing happens.
I think the whole logic should stay in this route/controller or I am missing something?
As requested I publish my solution:
Instead of embedding controller directly in Twig file and decided to handle my little form (just Search input, submitted by pressing "enter") with js. The reason for this is that it's impossible to redirect from embedded controller.
Code in twig:
<form id="top-search-form">
<div class="top-search">
<input id="search-string"
class="top-search__input" type="search"
placeholder="Search shop">
</div>
</form>
and code written in Javascript (requires FOSJSRouting Bundle):
const routes = require('/public/js/fos_js_routes.json');
import Routing from '/vendor/friendsofsymfony/jsrouting-bundle/Resources/public/js/router.min.js';
Routing.setRoutingData(routes);
document.addEventListener('DOMContentLoaded', function() {
const searchForm = document.getElementById('top-search-form');
searchForm.addEventListener('submit', function(e) {
e.preventDefault();
const searchString = document.getElementById('search-string').value;
var url = Routing.generate('items_filter', {
'searchText': searchString
});
location.href = url;
});
})

How to encrypt id in URL laravel

I want to encrypt the id in URL I'll show my controller code and route. I've already used Crypt::encrypt($id); in my controller but it's not working properly so I've commented that line in my controller
this is my controller
public function update(TenderRequest $request,$id){
$tender = TenderMaster::findOrFail($id);
//Crypt::encrypt($id);
if($request->extend_date < $request->end_date || $request->bid_status > 0){
return 'unsuccess';
} else{
$transaction = DB::transaction(function () use($request,$tender,$id) {
$tender->extend_date = $request->extend_date;
$tender->remarks = $request->remarks;
$tender->update($request->all());
});
return 'BID '.$tender->ref_no.' Succesfully Updated';
}
}
}
this is my route
Route::post('tender/update/{id}','Tender\TenderMasterController#update')->name('bid.update');
this is my blade
<form action="{{route('bid.update' ,Crypt::encrypt('id'))}}" class="form-horizontal" id="bid-update" method="POST">
{{ csrf_field() }}
#method('POST')
#include ('tender.form', ['formMode' => 'edit'])
</form>
Put this in your form action tag
<form action="/tender/update/{{Crypt::encrypt('id')}}" class="form-horizontal" id="bid-update" method="POST">
{{ csrf_field() }}
#method('POST')
#include ('tender.form', ['formMode' => 'edit'])
</form>
And replace this line of your controller:
$tender = TenderMaster::findOrFail($id);
With this:
$tender = TenderMaster::findOrFail(Crypt::decrypt($id));
And don't forget to add this line above in your controller
use Illuminate\Support\Facades\Crypt;
Hopefully it'll work
there's function encrypt and decrypt
but, i would like to disagree with idea of encrypting user id, its far from best practice
i would like to recommend you to use policy, policy guide
Use laravel builtin encryption to achieve this:
While adding your route in frontend, encrypt id with encryption helper like this:
{{route('bid.update', encrypt($id))}}
Now, In your controller, decrypt the id you have passed.
public function update($id, Request $request){
$ID = decrypt($id);
$tender = TenderMaster::findOrFail($ID);
..
...
}
I hope you understand.
Here is the docs:
https://laravel.com/docs/6.x/helpers#method-encrypt
https://laravel.com/docs/6.x/helpers#method-decrypt

Laravel unable to delete records, but methods are specified as delete

I want to delete records from database through my website. I have specified my methods as DELETE but it doesn't seem to be working.
In my form method, I have specified it as DELETE
<form method = "DELETE" action = "/admin_delete_bitstamp/{{ $data->bitstamp_api_id }}">
<button type = "submit" name = "delete" class = "btn">Delete</button>
</form>
In my routes file, I have also specified it as DELETE
Route::delete("/admin_delete_bitstamp/{id}", "Bitstamp_Access_C#destroy");
This is my delete function
public function destroy($id) {
$api = Bitstamp_Access_M::find($id);
$api->delete();
return redirect()->back();
}
The error message that I am getting is "The GET method is not supported for this route. Supported methods: DELETE."
I apologize if this is a rookie mistake.
Please try following code in view file:
<form method = "POST" action = "/admin_delete_bitstamp/{{ $data->bitstamp_api_id }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type = "submit" name = "delete" class = "btn">Delete</button>
</form>

Codeigniter: change URL after loading a View

I am working on a project which deals with lots of forms. I searched and tried the search results, but none of them worked.
My code view code "uprofile.php" is as follows:
<form class="form-horizontal" method="post" action='<?php echo base_url() . "home/addnewagency" ?>'>
<div class="form-group">
<label for="company" class="col-sm-3 control-label">New Agency Name:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="newagency" name="newagency" placeholder="Plase Enter New Agency Name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
My Controller "home.php" code is as follows:
public function addnewagency() {
$newagency = $this->input->post('newagency');
$this->dis_model->newagency_model(strtoupper($newagency));
$this->loadprofile();
}
public function loadprofile() {
$data['inscompanyname'] = $this->dis_model->getcompany();
$data['agentname'] = $this->dis_model->getagent();
$data['agencyname'] = $this->dis_model->getagency();
$data['clientname'] = $this->dis_model->getclient();
$data['deptname'] = $this->dis_model->getdept();
$this->load->view('uprofile', $data);
}
when I submit the form, the control is passed to addnewagency() data gets inserted in the database and the URL is http://localhost/dis/home/addnewagency. After getting back to the calling function, it goes to loadprofile() and loads the view uprofile. But, the URL still remains the same. But, I want it as http://localhost/dis/home/login and also want to pass the data. Does anyone have any idea regarding how to achieve this?
All positive suggestion are welcomed...
Thanks in advance...
Now you are calling $this->loadprofile() within addnewagency(). If you want to change URL, you need to use redirect() function of CodeIgniter.
Replace
$this->loadprofile()
with below line of code and it will work for you.
redirect(base_url() . 'home/loadprofile');
if you want to change the url use redirect(base_url() . 'home/loadprofile'); in your controller addnewagency(); as suggested by others and refer this question to know whether you can send data in redirect function or not,
Sending data along with a redirect in CodeIgniter
I found a alternative option to get this done.
You can't change URL string with $this->load->view function but you can redirect to target controller function using redirect method. Before you call redirect, set flash session data using $this->session->set_flashdata that will only be available for the next request, and is then automatically cleared. You can read it from official codeiginter documentation .
Example :
class Login extends CI_Controller {
public function index()
{
if ($this->session->login_temp_data) {
$data = $this->session->login_temp_data;
} else {
$data = array();
$data['name'] = 'Guest' ;
}
$this->load->view('login', $data);
}
public function get_name()
{
$data = [];
$data['name'] = 'John Doe';
$this->session->set_flashdata('login_temp_data', $data);
redirect("login");
}
}
You want to use the redirect() function
At the bottom of your addnewagency() method like so:
public function addnewagency() {
$newagency = $this->input->post('newagency');
$this->dis_model->newagency_model(strtoupper($newagency));
redirect(base_url() . 'home/loadprofile');
}

How To Pass GET Parameters To Laravel From With GET Method ?

i'm stuck at this very basic form, that i could not accomplish, which i want to build a search form with an text input, and two select controls, with a route that accept 3 parameters, the problem that when the i submit the form, it map the parameters with the question mark, not the Laravel way,
Markup
{{ Form::open(['route' => 'search', 'method' => 'GET'])}}
<input type="text" name="term"/>
<select name="category" id="">
<option value="auto">Auto</option>
<option value="moto">Moto</option>
</select>
{{ Form::submit('Send') }}
{{ Form::close() }}
Route
Route::get('/search/{category}/{term}', ['as' => 'search', 'uses' => 'SearchController#search']);
When i submit the form it redirect me to
search/%7Bcategory%7D/%7Bterm%7D?term=asdasd&category=auto
How can i pass these paramters to my route with the Laravel way, and without Javascript ! :D
The simplest way is just to accept the incoming request, and pull out the variables you want in the Controller:
Route::get('search', ['as' => 'search', 'uses' => 'SearchController#search']);
and then in SearchController#search:
class SearchController extends BaseController {
public function search()
{
$category = Input::get('category', 'default category');
$term = Input::get('term', false);
// do things with them...
}
}
Usefully, you can set defaults in Input::get() in case nothing is passed to your Controller's action.
As joe_archer says, it's not necessary to put these terms into the URL, and it might be better as a POST (in which case you should update your call to Form::open() and also your search route in routes.php - Input::get() remains the same)
I was struggling with this too and finally got it to work.
routes.php
Route::get('people', 'PeopleController#index');
Route::get('people/{lastName}', 'PeopleController#show');
Route::get('people/{lastName}/{firstName}', 'PeopleController#show');
Route::post('people', 'PeopleController#processForm');
PeopleController.php
namespace App\Http\Controllers ;
use DB ;
use Illuminate\Http\Request ;
use App\Http\Requests ;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
public function processForm() {
$lastName = Input::get('lastName') ;
$firstName = Input::get('firstName') ;
return Redirect::to('people/'.$lastName.'/'.$firstName) ;
}
public function show($lastName,$firstName) {
$qry = 'SELECT * FROM tableFoo WHERE LastName LIKE "'.$lastName.'" AND GivenNames LIKE "'.$firstName.'%" ' ;
$ppl = DB::select($qry);
return view('people.show', ['ppl' => $ppl] ) ;
}
people/show.blade.php
<form method="post" action="/people">
<input type="text" name="firstName" placeholder="First name">
<input type="text" name="lastName" placeholder="Last name">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" value="Search">
</form>
Notes:
I needed to pass two input fields into the URI.
I'm not using Eloquent yet, if you are, adjust the database logic accordingly.
And I'm not done securing the user entered data, so chill.
Pay attention to the "_token" hidden form field and all the "use" includes, they are needed.
PS: Here's another syntax that seems to work, and does not need the
use Illuminate\Support\Facades\Input;
.
public function processForm(Request $request) {
$lastName = addslashes($request->lastName) ;
$firstName = addslashes($request->firstName) ;
//add more logic to validate and secure user entered data before turning it loose in a query
return Redirect::to('people/'.$lastName.'/'.$firstName) ;
}
I had same problem. I need show url for a search engine
I use two routes like this
Route::get('buscar/{nom}', 'FrontController#buscarPrd');
Route::post('buscar', function(){
$bsqd = Input::get('nom');
return Redirect::action('FrontController#buscarPrd', array('nom'=>$bsqd));
});
First one used to show url like we want
Second one used by form and redirect to first one
So you're trying to get the search term and category into the URL?
I would advise against this as you'll have to deal with multi-word search terms etc, and could end up with all manner of unpleasantness with disallowed characters.
I would suggest POSTing the data, sanitising it and then returning a results page.
Laravel routing is not designed to accept GET requests from forms, it is designed to use URL segments as get parameters, and built around that idea.
An alternative to msturdy's solution is using the request helper method available to you.
This works in exactly the same way, without the need to import the Input namespace use Illuminate\Support\Facades\Input at the top of your controller.
For example:
class SearchController extends BaseController {
public function search()
{
$category = request('category', 'default');
$term = request('term'); // no default defined
...
}
}
Router
Route::get('search/{id}', ['as' => 'search', 'uses' => 'SearchController#search']);
Controller
class SearchController extends BaseController {
public function search(Request $request){
$id= $request->id ; // or any params
...
}
}
Alternatively, if you want to specify expected parameters in action signature, but pass them as arbitrary GET arguments. Use filters, for example:
Create a route without parameters:
$Route::get('/history', ['uses'=>'ExampleController#history']);
Specify action with two parameters and attach the filter:
class ExampleController extends BaseController
{
public function __construct($browser)
{
$this->beforeFilter('filterDates', array(
'only' => array('history')
));
}
public function history($fromDate, $toDate)
{
/* ... */
}
}
Filter that translates GET into action's arguments :
Route::filter('filterDates', function($route, Request $request) {
$notSpecified = '_';
$fromDate = $request->get('fromDate', $notSpecified);
$toDate = $request->get('toDate', $notSpecified);
$route->setParameter('fromDate', $fromDate);
$route->setParameter('toDate', $toDate);
});

Categories