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

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

Related

How to pass the value from controller to header file

I need to pass the data from the controller to a header file inside partials folder.
Suggest me how to pass the data "currency" from the controller to the header file.
Controller :
class HeaderController extends Controller
{
public function rate(){
$currency = Whmcs::GetCurrencies([
]);
return view('partials.header',compact('currency'));
}
}
Header file:
<form name="form">
<select name="currency" class="form-control">
#foreach($currency['currencies']['currency'] as $key=>$value)
#for($key=0;$key<100;$key++)
#endfor
<option value="{{$value['code']}}">{{$v=$value['code']}}</option>
#endforeach
</select>
</form>
Route:
Route::any('/partials.header', 'HeaderController#rate');
You can make this via laravel view composer method as below:
Add this method in App/Providers/ComposerServiceProvider.php in boot method
view()->composer(['partials.header'], function ($view) {
$currency = Whmcs::GetCurrencies([]);
$view->with('currency', $currency);
});
Then you can use $currency variable to your header file you don't need to pass it from any controller.
You can achieve this :
return view('partials.header', ['currency' => $currency]);
Your data should be an array with a key-value pair.
You can also use with method:
return view('partials.header')->with('currency', $currency);
Also, you can use compact :
return view('partials.header', compact('currency'));
For more, please refer Passing Data To Views

How to pass value inside href to laravel controller?

This is code snippet from my view file.
#foreach($infolist as $info)
{{$info->prisw}} / {{$info->secsw}}
#endforeach
Here is my route which I defined inside route file
Route::get('switchinfo','SwitchinfoController');
I want to pass two values inside href tag to above route and retrieve them in controller. Can someone provide code to do this thing?
Since you are trying to pass two parameters to your controller,
You controller could look like this:
<?php namespace App\Http\Controllers;
class SwitchinfoController extends Controller{
public function switchInfo($prisw, $secsw){
//do stuffs here with $prisw and $secsw
}
}
Your router could look like this
$router->get('/switchinfo/{prisw}/{secsw}',[
'uses' => 'SwitchinfoController#switchInfo',
'as' => 'switch'
]);
Then in your Blade
#foreach($infolist as $info)
Link
#endforeach
Name your route:
Route::get('switchinfo/{parameter}', [
'as'=> 'test',
'uses'=>'SwitchinfoController#function'
]);
Pass an array with the parameters you want
<a href="{{route('test', ['parameter' => 1])}}">
{{$info->prisw}} / {{$info->secsw}}
</a>
and in controller function use
function ($parameter) {
// do stuff
}
Or if don't want to bind parameter to url and want just $_GET parameter like url/?parameter=1
You may use it like this
Route::get('switchinfo', [
'as'=> 'test',
'uses'=>'SwitchinfoController#function'
]);
function (){
Input::get('parameter');
}
Docs
You can simply pass parameter in your url like
#foreach($infolist as $info)
<a href="{{ url('switchinfo/'.$info->prisw.'/'.$info->secsw.'/') }}">
{{$info->prisw}} / {{$info->secsw}}
</a>
#endforeach
and route
Route::get('switchinfo/{prisw}/{secsw}', 'SwitchinfoController#functionname');
and function in controller
public functionname($prisw, $secsw){
// your code here
}

How to pass multiple arguments with url (routing) in laravel 5.1

LARAVEL 5.1
I want to edit my table which having ID and TktID.
I want to pass this two parameters to edit method of my TestController.
My link:
<a href="/sig/edit?id={{$value->id}}&ticketid={{$value->ticketid}}" title="Edit signature">
My route.php
Route::get('sig/edit{id}{ticketid}','TicketsController#edit');
edit method of controller:
public function edit($id, $ticketid)
{
//
}
How do I pass here two arguments in route.php to controller.
You forget end bracket
You have error in your routes.php file:
Route::get('sig/edit{id}{ticketid}', 'TicketsController#edit');
Should be:
Route::get('sig/edit/{id}/{ticketid}', 'TicketsController#edit');
Notice the forward slash after edit and id.
And in the view it should be either of the following:
<a href="{{ url('sig/edit/ ' . $value->id . '/' . $value->ticketid .')}}" title="Edit signature">
Or
<a href="/sig/edit/{$value->id}/{$value->ticketid}" title="Edit signature">
I hope this helps you out. Cheers.
Route
Route::get('sig/edit{id}{ticketid}','TicketsController#edit')->name(sig.edit);
link
<a href="{{route('sig.edit',[$value->id,$value->ticketid])}}" title="Edit signature">
<a class="getValues" href="/sig/edit" title="Edit signature"/>Edit</a>
<input type="hidden" id="id" name="id" value"={{$value->id}}"/>
<input type="hidden" id="ticketid" name="ticketid" value="{{$value->ticketid}}"/>
jQuery(document).ready(function(){
var $id=jQuery('#id').val();
var $ticketid=jQuery('#ticketid').val();
jQuery('getValues').on('click',function(){
$.ajax({
url:'yourController/controller'sFunction',
data:{'id':$id,'ticketid':$ticketid},
}).success(function(response){
alert(rseponse);
});
})
});
paste this line of code as first line in your controller's function ...
$inputs = Input::all();
and get values of input like
echo $ticketid=$inputs['ticketid'];
echo "<br/>";
echo $id=$inputs['id'];
In my case, I am passing two parameters like this:
ROUTES
Route::get('/add/{debitid}/{creditid}',
['as'=>'loan_add',
'uses'=>'LoanController#loanset']);
In LoanController
public function loanset($debitid, $creditid)
{
$debit_user= UserModel::findOrFail($debitid);
$credit_user= UserModel::findOrFail($creditid);
return view('load.add',compact('debit_user','credit_user'));
}
This example might be helpful.
I found this way to keep your URL the same way and access multiple parameters
<a href="/sig/edit?id={{$value->id}}&ticketid={{$value->ticketid}}" title="Edit signature">
Route
Route::get('sig/edit', 'TicketsController#edit');
Access the parameter values in the controller
Controller
public function edit(){
$id = Input::get('id');
$ticketId = Input::get('ticketid');
}
Note: import Input in controller
use Illuminate\Support\Facades\Input;
in routes/web.php file - This one works for me.
Route::any('/documents/folder/{args?}', function($args){
$args = explode('/', $args);
return $args;
})->where('args', '(.*)');
It should handle every argument/parameter now.
Hope it works !
As you are passing the parameters like this ?name=value, you dont have to set up the route for it , you can directly access it in your controller by Dependency injection
you have to add this above your class
use Illuminate\Http\Request;
Then in controller inject it & fetch the parameter values by name:
public function edit(Request $request)
{
//
$id= $request->id;
$tkt= $request->tkt_id;
}

Laravel Routing and Controller for Search

I'm building my first basic laravel web app, after following a few tutorials this is the first one I'm tinkering with on my own. I'm running into to some trouble with routing to a controller and then getting the correct url.
Ideally at this point I should only have two routes / and /{user}. On the homepage you can search via a form for the user and the form should take you to /{user}.
Routes (I have three cause I'm still trying to get this to work, and I think I need a POST):
Route::get('/', 'HomeController#index');
Route::get('/{user}', 'HomeController#student');
Route::post('/', 'HomeController#studentLookUp');
Home Controller:
public function index()
{
return View::make('helpdesk');
}
public function student($user) {
return View::make('selfservice')
->with('user', $user);
}
public function studentLookUp() {
$user = Input::get('ID');
return View::make('selfservice')
->with('user', $user);
}
Form:
{{ Form::open(array('class'=>'navbar-form navbar-left', 'role'=>'search'), array('action' => 'HomeController#student')) }}
<div class="form-group">
{{ Form::text('ID', '', array('placeholder'=>'ID', 'class'=>'form-control') ); }}
</div>
{{ Form::button('Search', array('class'=>'btn btn-default')) }}
{{ Form::close() }}
At this point I can search from the homepage ('/') and it will take me back to the homepage but with the searched for user which is how I want it to work except it doesn't have the right url of homepage.com/username.
Any help would be much appreciated!
First register a route to listen your search request:
1. Search Route:
Register search route.
//route search
Route::get('/search',['uses' => 'SearchController#getSearch','as' => 'search']);
2. Search View:-
Now create a search form in a view:-
<form action="/search" method="get">
<input type="text" name="q" placeholder="Search.."/>
<button type="submit">Search</button>
</form>
3. SearchController :
Now create SearchController to handle your searching logic.
SearchController :
<?php
class SearchController extends \BaseController {
public function getSearch()
{
//get keywords input for search
$keyword= Input::get('q');
//search that student in Database
$students= Student::find($keyword);
//return display search result to user by using a view
return View::make('selfservice')->with('student', $students);
}
}
Now you have to create one view selfservice to display your search result.
4. Selfservice View:
#foreach ($students as $key=> $student)
<div>
{{$student->name}}
</div>
#endforeach
Here for each student result, one link will be created. That link will be link:-
website.domain/{student}
5. Update Routes for Student
Route::get('/{student}',['uses' => 'HomeController#student','as' => 'student.show']);
UPDATE updated the answer to get student page directly
To redirect from search to website.domain\{user} follow these steps:-
1. Modify SearchController
<?php
class SearchController extends \BaseController {
public function getSearch()
{
//get keywords input for search
$keyword= Input::get('q');
//search that student in Database
$student= Student::find($keyword);
//redirect directly to student.show route with student detail
return Redirect::route('student.show', array('student' => $student));
}
}
2. Now add a function for Route student.show in HomeController
Route::get('/{student}',['uses' => 'HomeController#student','as' => 'student.show']);
In HomeController
public function student($student)
{
//here display student detail
}

Missing argument Laravel controller function edit

I have a problem with this
I have un list of articles, and each element has a button to edit, how the next code:
<p>modifier l'article</p>
and I'm sending to the file route:
Route::get('/edit', 'ArticleController#edit');
to the file ArticleController method edit:
public function edit($idarticle)
{
$artic=article::find($idarticle);
if(is_null ($artic))
{
App::abort(404);
}
$form_data = array('route' => array('article.update', $artic->idarticle), 'method' => 'PATCH');
$action = 'modifier';
return View::make('article.create')->with('artic', $artic);
}
then I don't understand my error
Probably change Route::get('/edit', 'ArticleController#edit'); to Route::get('/edit/{idarticle}', 'ArticleController#edit');
Also
<p>modifier l'article</p>
needs to be
<p>modifier l'article</p>
The parameter in the router is not passed as an html parameter, but rather a part of the URL. So combines these two changes, it should be working.

Categories