[php] 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

This question is related to php forms laravel

The answer is


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

        ...
    }
}

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


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

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.


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

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

        ...
    }
}

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory