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
Related
$cartItems contains all the rows of products from database and I am using this inside a blade file.
I want to pass this $cartItems back to a controller from this blade file
Note: $cartItems is from index() function in a controller like below.
$cartItems = DB::table('products')->whereIn('id', $cartItemsArray)->get();
return view('cart.index', compact('cartItems')
Below is my code.
index.blade.php
Proceed to checkout
web.php
Route::get('/cart/checkout/{cartItems}', 'CartController#checkout')->name('cart.checkout')->middleware('auth');
CartController.php
public function checkout($cartItems)
{
dd($cartItems);
return view('cart.checkout');
}
The error I am getting is,
Missing required parameters for [Route: cart.checkout] [URI: cart/checkout/{cartItems}]. (View: E:\github\LARAVEL\Deal-Ocean\resources\views\cart\index.blade.php)
You can use a form to send data back to server
Update your route from get to post
Route::post('/cart/checkout', 'CartController#checkout')->name('cart.checkout')->middleware('auth');
Use a form to post data to server. You can pass any additional data along with the request as well.
<form method="post" action="/cart/checkout">
#foreach($cartItems as $item)
<input name="cartItems[]" value="{{ $item->id }}"
#endforeach
<button class="site-btn">Proceed to checkout</button>
</form>
And in your controller use Request to access data
public function checkout(Request $request)
{
$cartItems = DB::table('products')->whereIn('id', $request->get($cartItems))->get();
dd($cartItems);
return view('cart.checkout');
}
If you want to proceed with the get request you should be able to do as follow
As $cartItems is a collection of products. So you can send the product ids and query the products using the ids from request.
<a href="{{ route('cart.checkout', ['cartItems' => $cartItems->pluck('id')->toArray()]) }}"
class="site-btn">Proceed to checkout</a>
Update controller
public function checkout(Request $request)
{
$cartItems = DB::table('products')->whereIn('id', $request->get($cartItems))->get();
dd($cartItems);
return view('cart.checkout');
}
Why use the same code logic of the index() method in the checkout method in the
CartController.
the checkout method will look like this:
$cartItems = DB::table('products')->whereIn('id', $cartItemsArray)->get();
return view('cart.checkout', compact('cartItems');
Welcome ! I have a problem . I try to connect via relations two models. If i create note it belongs to only one user. Problem is that in form options don't know why it doesn't display me users from database.
NotesController :
public function create()
{
$data['pilots'] = Pilot::all();
return view('uwagi.create',$data);
}
Create blade:
<label>Pilot</label>
<select class="form-control" id="pilot" name="pilots[]">
#foreach($pilots as $pilot)
<option value="{!! $pilot->id !!}"
{!! $pilot->name !!}
</option>
#endforeach
</select>
Regards and thank u for help
You are sending variable named $data but your foreach loop doesnot contain data variable, why?
public function create()
{
$pilots = Pilot::all();
return view('uwagi.create',$pilots);
}
Hope it's helps you.
pls modify your controller like this
public function create()
{
$pilots = Pilot::all();
return view('uwagi.create', compact('pilots'));
}
here's my form code :
<div class="form-group">
<label>Warranty:</label>
{{ Form::checkbox('warranty', 0, false) }}
</div>
here's my controller code :
public function save(Request $request, $obj = null) {
if (!$obj) {
$obj = new Service;
}
(Input::has('warranty')) ? true : false;
return $this->saveHandler($request, $obj);
}
it throws this error Class 'App\Http\Controllers\Input' not found
any idea ?
You can use request object to get the warranty input as:
$request->get('warranty')
or
$request->has('warranty')
$request->merge(array('checkbox_name' => $request->has('checkbox_name') ? true : false));
Object::create($request->all());
This is how I save boolean parameters which are checkboxes in form.
Or simply give your checkbox value
{{ Form::checkbox('checkbox_name', 1) }}
Add this at top in the controller,
use Illuminate\Support\Facades\Input;
Input facade was removed in latest verison, so you can add it to config/app.php:
'Input' => Illuminate\Support\Facades\Input::class,
Or add this line to the beginning of a controller:
use Illuminate\Support\Facades\Input;
Or write full path when you use it:
(\Illuminate\Support\Facades\Input::has('warranty')) ? true : false;
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;
}
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);
});