How to pass default values to controller by routing in Laravel 5? - laravel

In laravel, if I want to pass parameters to a controller in my route file
Route::get('user/sk/{id}' , 'UsersController#findsk');
If I want to pass default parameters:
Route::get('user/{name?}', function ($name = 'John') {
// how do I invoke my controller here?
return $name;
});
How do I merge the two things? Is there a shortcut?
Route::get('user/sk/{id}' , 'UsersController#findsk'
// can I add an array of default parameters here?
);

As far as I know, there is no shortcut, unfortunately.
To inject one optional parameter:
Route::get('user/{name?}', function ($name = 'John') {
$ctrl = new \App\Http\Controllers\UsersController();
return $ctrl->findsk($name);
});
To inject one optional parameter with more parameters:
Assuming you had an $id param and that UsersController#findsk accepts $id and $name.
Route::get('user/{id}/{name?}', function ($id, $name = 'John') {
$ctrl = new \App\Http\Controllers\UsersController();
return $ctrl->findsk($id, $name);
});
To inject something in the controller from the router:
Assuming want to use a url as a switch.
Route::get('my-special-url', function () {
$ctrl = new \App\Http\Controllers\UsersController();
return $ctrl->findsk(1, 'Paul');
});

You can pass as a default parameter to function in your controller like just normal function
Route::get('user/sk/{id}' , 'UsersController#findsk');
in UsersController
function findsk($id ='myVal'){
}

Related

Passing several, optional, key/value pairs in URL with Laravel

I am making a project management application in Larvel. TaskController#index queries the db and return tasks. To be efficient and elegant, I want to be able to pass it several, optional, key/value pairs in the URL, like /tasks/org_id/36/status/open or /tasks/proj_id/1557/status/closed, and have it return the tasks based on those variables. My code is below, but the problem is getting the route to be able to receive the optional key/value pairs. Also, they shouldn't all have to all be submitted all of the time if they aren't needed.
Route/web.php:
Route::get('/tasks/status/{status}/proj_id/{proj_id}/user_id/{user_id}/org_id/{org_id}
/creator_id/{creator_id}', 'TaskController#index')->name('tasks.index');
Route::resource('tasks', 'TaskController')->except([
'tasks.index'
]);
Controller:
class TaskController extends Controller
{
public function index($proj_id = null, $recipient_id = null, $org_id = null, $creator_id = null, $status = null)
{
$tasks = Task::where('recipient_id', auth()->user()->id)
->when($status, function ($query, $status) {
return $query->where('status', $status);
})
->when($recipient_id, function ($query, $recipient_id) {
return $query->where('recipient_id', $recipient_id);
})
->when($public, function ($query, $public) {
return $query->where('public', $public);
})
->get();
return view('tasks.index', compact('tasks'));
}
How do I get the route to be able to accept a variety of optional key/value pairs?
For your convenience, work with GET (?status=...&...=...) parameters and work through them in a global middleware. It will possibly eliminate a lot of confusion as your project grows.
In the middleware you could do something like this:
public function handle($request, Closure $next)
{
$params = array();
//OR look them up individually:
$params['status'] = $request->query('status');
$params['proj_id'] = $request->query('proj_id');
$params['org_id'] = $request->query('org_id');
//OR get all query requests at once:
$params = $request->query();
//and set them as a session value
$request->session()->put('params', $params);
return $next($request);
}
Access the possible values anywhere in the project with the helper session('params')['status']. If there is no value in the url, it's defaulted to null.
Addition: to help you out building the query params for the url you may want to have a look at the PHP function http_build_query()
try this:
i think fix your problem
Route::resource('tasks', 'TaskController')->except([
'index'
]);
Route::get('/tasks/status/{status}/proj_id/{proj_id}/user_id/{user_id}/org_id/{org_id}
/creator_id/{creator_id}', 'TaskController#index');
i hope help you
https://laracasts.com/discuss/channels/laravel/routeresource-parameters

Passing route parameter to controller Laravel 5

I'm trying to pass a route parameter to controller, but I get this error : Argument 2 passed to App\Http\Controllers\JurnalController::store() must be an instance of App\Http\Requests\JurnalRequest, none given
Below are the codes ..
Route :
Route::get('/edisi/{id}', 'JurnalController#store');
Controller :
public function store($id, JurnalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
So my question is how to pass the route parameter properly ? Thank you
new routes :
Route::get('/', function () {
return view('pages/home');
});
Route::group(['middleware' => ['web']], function () {
Route::get('edisi', 'EdisiController#index');
Route::get('edisi/create', 'EdisiController#create');
Route::get('edisi/{edisi}', 'EdisiController#show');
Route::post('edisi', 'EdisiController#store');
Route::get('edisi/{edisi]', 'EdisiController#edit');
Route::patch('edisi/{edisi}', 'EdisiController#update');
Route::delete('edisi/{edisi}', 'EdisiController#destroy');
});
Route::get('/edisi/{id}', 'JurnalController#storejurnal');
Route::group(['middleware' => ['web']], function () {
Route::get('jurnal', 'JurnalController#index');
Route::get('jurnal/create', 'JurnalController#create');
Route::get('jurnal/{jurnal}', 'JurnalController#show');
Route::post('jurnal', 'JurnalController#storejurnal');
Route::get('jurnal/{jurnal}/edit', 'JurnalController#edit');
Route::patch('jurnal/{jurnal}', 'JurnalController#update');
Route::delete('jurnal/{jurnal}', 'JurnalController#destroy');
});
new storejurnal method :
public function storejurnal(JurnalRequest $request, $id) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Edisi::findOrFail($id)->jurnal()->create($input);
return redirect('jurnal');
}
When you are using resource controller, the store method does not accept any other argument except the Request instance. Try changing the method name or remove the second argument. store() method be default accepts post requests not get requests. Either put your route on top of the resource controller or change the method name.
Route::get('/edisi/{id}', 'JurnalController#store');
Route::resource('jurnals', 'JurnalController');
I hope this helps.
The correct format is:
public function store(JurnalRequest $request, $id) {
// your code
}
If you receive an argument such as Missing argument 2 as suggested in your comments, it means that either you aren't generating the routes correctly, or the url doesn't include the id segment.

Laravel cookie in serviceprovider not comparable

I try to pass a variable based on a cookie value in my compose function to all my view to build my menu, with the use of serviceproviders recommmended here:
File: Providers/ViewComposerServiceProvicer.php
public function boot(Request $request) { $this->composeTopBar($request);}
public function composeTopBar(Request $request)
{
$cookieValue = $request->cookie('brand');
// if value not set use default value.
if($cookieValue == null)
{
$cookieValue = 1;
}
$brands = \App\Brand::orderBy('priority', 'asc')->get();
foreach($brands as $brand){
if($brand->id == $cookieValue){
$brand->menuActive = true;
}
else{
// show value to debug
$brand->menuActive = $cookieValue;
}
}
view()->composer('front.layouts.top', function ($view) use ($brands) {
$view->with('brandItems',$brands );
});
}
the cookieValue looks like
yJpdiI6IlNJODBvQ1RNM004OWVleyJpdiI6IlNJODBvQ1RNM004OWVleyJpdiI6IlNJODBvQ1RNM004OWVl
While the value in my controller looks like '2' How can i get the original value 2 in my compose function?
I need to get the original value to compare it in my composeTopBar function so I can pass a variable to be true if it equals the cookie value.
Method to set cookie
$response = response()-> view('front.products.category', compact('products','category'));
$response->withCookie(cookie()->forever('brand',1));
return $response;
I ended up using a class based composer .
The reason why this works is because it's called later in the lifecycle of laravel and the Cookie variables are decrypted. When using Closure based composers the values are encrypted.
Try this: put the view() call as a parameter to response().
$response = response(view('front.products.category', compact('products','category')));
$response->withCookie(cookie()->forever('brand', 1));
return $response;

Routing to controller with optional parameters

I'd like to create a route that takes a required ID, and optional start and end dates ('Ymd'). If dates are omitted, they fall back to a default. (Say last 30 days) and call a controller....lets say 'path#index'
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(!$start)
{
//set start
}
if(!$end)
{
//set end
}
// What is the syntax that goes here to call 'path#index' with $id, $start, and $end?
});
There is no way to call a controller from a Route:::get closure.
Use:
Route::get('/path/{id}/{start?}/{end?}', 'Controller#index');
and handle the parameters in the controller function:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
This helped me simplify the optional routes parameters (From Laravel Docs):
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
Or if you have a controller call action in your routes then you could do this:
web.php
Route::get('user/{name?}', 'UsersController#index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
I hope this helps someone simplify the optional parameters as it did me!
Laravel 5.6 Routing Parameters - Optional parameters
I would handle it with three paths:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
Note the order - you want the full path checked first.
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Find more details here (Laravel 7) : https://laravel.com/docs/7.x/routing#parameters-optional-parameters
You can call a controller action from a route closure like this:
Route::get('{slug}', function ($slug, Request $request) {
$app = app();
$locale = $app->getLocale();
// search for an offer with the given slug
$offer = \App\Offer::whereTranslation('slug', $slug, $locale)->first();
if($offer) {
$controller = $app->make(\App\Http\Controllers\OfferController::class);
return $controller->callAction('show', [$offer, $campaign = NULL]);
} else {
// if no offer is found, search for a campaign with the given slug
$campaign = \App\Campaign::whereTranslation('slug', $slug, $locale)->first();
if($campaign) {
$controller = $app->make(\App\Http\Controllers\CampaignController::class);
return $controller->callAction('show', [$campaign]);
}
}
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
});
What I did was set the optional parameters as query parameters like so:
Example URL:
/getStuff/2019-08-27?type=0&color=red
Route:
Route::get('/getStuff/{date}','Stuff\StuffController#getStuff');
Controller:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}
Solution to your problem without much changes
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
return App\Http\Controllers\HomeController::Path($id,$start,$end);
});
and then
class HomeController extends Controller
{
public static function Path($id, $start, $end)
{
return view('view');
}
}
now the optimal approach is
use App\Http\Controllers\HomeController;
Route::get('/path/{id}/{start?}/{end?}', [HomeController::class, 'Path']);
then
class HomeController extends Controller
{
public function Path(Request $request)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
//your code
return view('view');
}
}

CodeIgniter Controller Method Parameters Issue

I'm using codeigniter 2.1 and I defined a function as follows.
public function reset($email, $hash) {
}
According to MVC architecture and OOPS concept, the function could not execute if I did not pass the parameters in the url. But in codeigniter this function gets executing, So how can i overcome this?. Please help me to find solutions.
Just you need to define null parametra like this:
public function reset($email = null, $hash = null) {
}
If you call function
(controller name)/reset/mail#mail.com/dsadasda
than $email = mail#mail.com & $hash = dsadasda
if you function
(controller name)/reset
than $email and $hash will be null.
Also you can declare default parametre like this.
public function reset($email = mail#mail.com, $hash = dsadasdas) {
}
Hope that I was clear.
If you want to execute function with or without parameters
you can set default values for it.
public function reset($email = '', $hash = '') {
}
This way when there are no parameters function can still execute.
You can use condition for code
public function reset($email = '', $hash = '') {
if(!empty($email) AND !empty($hash)){
//your code here
}
}

Resources