Laravel cookie not set on home page but is set everywhere else - php

We have this function in helpers.php that returns the lang
function locale() {
if(Cookie::has('locale') && array_key_exists(Cookie::get('locale'), Config::get('languages'))) {
$locale = Cookie::get('locale');
} else {
$locale = 'en';
}
return $locale;
}
On every single page, it works and returns the correct value. But, for some reason, on the index page only, it is always 'en'.
This is how we set it:
function setLocale(Request $request) {
$locale = $request->input('locale');
if(array_key_exists($locale, \Config::get('languages'))) {
$cookie = cookie()->forever('locale', $locale);
\App::setLocale($locale);
}
return redirect()->back()->withCookie($cookie);
}

Whoops, it seems the error was that the home page route was in a group with the web middleware, but we were still setting it
Route::get('/', [
'uses' => 'HomeController#index',
'as' => 'root',
'middleware' => 'web'
]);
removing the middleware from this part since it's already present in the route group solved the issue.

Related

Laravel, need show route url domen/specialist/id

I want show domen url user id after signin, example domen/specialist/id.
ALREADY AS DAY 2 IT IS NOT RECEIVED TO DO. Maybe I'm doing something wrong help please.
This my web.php code
// Front End Routes
Route::group([
'namespace' => 'landing',
'middleware' => 'groups',
], function (){
Route::get('/', 'PagesController#index')->name('landing.index');
Route::get('/specialist/{id}', 'SpecialistDashboardController#dashboard')-
>name('frontend.specialist.dashboard');
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
});
Specialist Dashboard Controller code
class SpecialistDashboardController extends Controller
{
public function dashboard($id){
$id = Auth::user()->id;
return view('Frontend.specialists.dashboard.index');
}
public function profile_settings(){
return view('Frontend.specialists.profile_settings.index');
}
}
GroupsMiddleware
public function handle($request, Closure $next)
{
// ADMIN = 5
if (\Auth::check() && Auth::user()->groups == 5){
return $next($request);
}
// PATIENTS = 1
elseif(\Auth::check() && Auth::user()->groups == 1){
return redirect()->route('landing.index');
}
// SPECIALISTS = 3
elseif (\Auth::check() && Auth::user()->groups == 3){
return redirect()->route('frontend.specialist.dashboard');
}
}
Error message:
Missing required parameters for [Route: frontend.specialist.dashboard] [URI: specialist/{id}].
Your frontend.specialist.dashboard route requires a id paramter but you didn't provide any when redirecting. Also looking at your SpecialistDashboardController, the $id can be omitted since you're overwriting it with Auth::id().
Try doing this:
# remove the {id} param
Route::get('/specialist', 'SpecialistDashboardController#dashboard')-
>name('frontend.specialist.dashboard');
class SpecialistDashboardController extends Controller
{
...
public function dashboard(){ // remove the $id param
$id = Auth::user()->id;
return view('Frontend.specialists.dashboard.index');
}
...
}
But if in any case you need the id param, you can provide the value for it in redirect by doing
return redirect()->route('frontend.specialist.dashboard', ['id' => $id]);

Only Login Work with switch language in laravel

I use two languages in my website. In the first, I could switch languages easy but I don't know what happened.
Now I can switch language if I login (auth) but if I login as guest I can't switch languages anymore.
This is my route:
// Routes
Route::get('locale', function () {
return \App::getLocale();
});
Route::get('locale/{locale}', function ($locale) {
\Session::put('locale', $locale);
return redirect()->back();
});
Route::post('/language-chooser', 'LanguageController#changeLanguage');
Route::post('/language/', array(
'before' => 'csrf',
'as' => 'language-chooser',
'uses' => 'LanguageController#changeLanguage'));
// Controller
public function changeLanguage(Request $request)
{
if ($request->ajax())
{
$request->session()->put('locale',$request->locale);
$request->session()->flash('alert-success',
('app.locale_change_success'));
}
}
// Middlware
public function handle($request, Closure $next)
{
if ( Session::has('locale')) {
$locale = Session::get('locale', Config::get('app.locale'));
} else {
$locale = 'en';
}
App::setLocale($locale);
return $next($request);
}
}
// View
<select id="LanguageSwitcher" >
<option value="en" <?php $cuRRlocal = Config::get('app.locale');
echo ($cuRRlocal == 'en' ? "selected" : "") ?>>English</option>
<div class="dropdown-divider"></div>
<option value="ar" <?php $cuRRlocal = Config::get('app.locale');
echo ($cuRRlocal == 'ar' ? "selected" : "") ?> >Arabic</option>
</select>
when i try change language and i not authenticated nothing happened
i elso did this but nothing happend
public function __construct()
{
$this->middleware('auth',['except'=>['changeLanguage']]);
}
If you can switch language when logged in as auth, then I think you have protected the LanguageController with the auth middleware, can you describe what happen when you want to change language and are not authenticated?.
Just check the language controller constructor if it's having the auth middleware. and if that is the case, then you will want remove the following code to a different controller that is accessible to both the authenticated user and unauthenticated users.
public function changeLanguage(Request $request)
{
if ($request->ajax())
{
$request->session()->put('locale',$request->locale);
$request->session()->flash('alert-success',
('app.locale_change_success'));
}
}
I Fix Problem by Add
#csrf
before pages
cuz i was write this line
Route::post('/language/', array( 'before' => 'csrf', 'as' => 'language-chooser', 'uses' => 'LanguageController#changeLanguage')); // Controller

Laravel forgets session after redirect

I was able to use this to redirect to another route and pass data to it as well:
public function method() {
$dir = "A";
$name = "ABC";
return redirect()->route('catch')->with([
'dir' => $dir,
'name' => $name
]);
}
public function catch() {
dd(Session::has('dir'));
dd(Session::has('name'));
}
Above code was working until today
Then I tried setting session and checking within the method:
public function method() {
Session::put('dir', 'a');
Session::put('name', 'abc');
Session::has('dir'); // true
return redirect()->route('catch');
}
public function catch() {
Session::has('dir'); // false
}
(this works because of route Route::get('/catch', ['as' => 'catch', 'uses' => Controller#catch])...)
This was working until a second ago and I was messing up with nginx user permissions, then it stopped working

Laravel check if all route resourrce params are set

I am making a API, i want to check if the posted params (by curl) are equal to de resource params. If not i want to return a json with errors.
How do I get it done to check all route resource parameters?
Route::group(['prefix' => 'api' , 'middleware' => 'auth:api'], function () {
Route::resource('note' , 'NoteController');
});
You can handle the MethodNotAllowedHttpException in Exception/Handler.php in method render
public function render($request, Exception $e)
{
// check if MethodNotAllowedHttpException exception type using status code 405 or instanceof
if ($e->getStatusCode() == 405) {
// custom your response. could be json with 404 or redirect to another page
return response()->json(['error' => true, 'message' => 'not found'], 404);
}
return parent::render($request, $e);
}
more explanation here
The answer is:
Routes.php
Route::put('note', 'NoteController#update');
Controller:
$id = null and make a check id check
public function update(Request $request, $id = null){
if($id != null){
//do stuff
}

CakePHP 3: Different login redirection depending on user roles

I'm using CakePHP 3 and trying to change the default route after user is logged in. I want to set default route different depends on user's role_id.
I found a solution but it's only for CakePHP 2.
I can't use it in CakePHP 3, I can't use Session component in bootstrap.
So I tried this in my AppController
public $redirects = [
'admin' => ['controller' => 'Clients', 'action' => 'statistics'],
'user' => ['controller' => 'Clients', 'action' => 'index'],
];
public function initialize()
{
parent::initialize();
...
if ($this->Auth->user())
Configure::write('Route.default', $this->redirects[$this->Auth->user('role_id')]);
else
Configure::write('Route.default', ['controller' => 'Users', 'action' => 'login']);
Router::scope('/', function($routes) {
$routes->connect('/', Configure::read('Route.default'));
$routes->fallbacks('InflectedRoute');
});
}
My default route is
$routes->connect('/', \Cake\Core\Configure::read('Route.default'));
And I defined Route.default in bootstrap.php as
Configure::write('Route.default', ['controller' => 'Users', 'action' => 'login']);
But when I open the / page I still see the users/login page even if I have already logged in
So I added the redirection before Router::scope
if (
$this->Auth->user()
&& $this->request->params['controller'] == 'Users'
&& $this->request->params['action'] == 'login'
) {
$this->redirect(Configure::read('Route.default'));
}
Could anyone help me with that?
We can check user role from session data and make redirect according the role.
We can edit in the users controllers login function as follows
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$loggedUser = $this->request->session()->read('Auth.User');
if($loggedUser['role'] == 'customer'){
return $this->redirect('/');
}else if($loggedUser['role'] == 'admin'){
return $this->redirect('/admin');
}else{
return $this->redirect($this->Auth->redirectUrl());
}
}
}
}
My cakephp version is 3.3.8
hey i found a solution!
create an file in App\Routing\Filter like that:
<?php
namespace App\Routing\Filter;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;
class HFilter extends DispatcherFilter {
public function beforeDispatch(Event $event) {
$request = $event->data['request'];
if (isset($request->url) && $request->url == '') {
if ($request->session()->read('Auth.User')){
$request->params['controller'] = 'Users';
$request->params['action'] = 'index';
} else {
$request->params['controller'] = 'Pages';
$request->params['action'] = 'home';
}
}
}
}
?>
after add it into the bootstrap.php file without the Filter in the name like that
DispatcherFactory::add('H');
DispatcherFactory::add('Asset');
DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');

Categories