Laravel cookie in serviceprovider not comparable - laravel

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;

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

When using a {domain} wildcard, is there a way to globally set the route( ['domain' => $domain] ) property (not at a function level)

Laravel 5.5
Using a group in RouteServiceProvider for {domain}
I want to be able to call Named Routes in blade without having to pass
public function pageName($domain){
return view('mypage', ['domain'=>$domain,'othervars'=>$domain)])
}
and avoid this mess in blade:
{{ route('nameOfRoute', ['domain'=>$domain]) }}
Instead i would love to simply in my route group set the route(['domain']) property to be $domain and be done with it.
No global way to set it, but instead, wrap the route('name') default helper function with my own helper function, and add the param to the array.
Example function:
function orgRoute($route, $params = [])
{
if (!is_array($params)){
$params = [$params];
}
// Set the domain value if not set, null, or jibberish
if (!isset($params['domain']) || $params['domain']=='{domain}' || $params['domain'] == '')
{
// Instance of App Domain is set in OrgBaseController __construct()
$domain = \App::make('current_domain');
$params['domain'] = $domain;
}
return route($route, $params);
}

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

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'){
}

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