I have a route that creates several database entries. After the creation I'd like to forward to a route that fetches those entries and displays them.
This is the route for fetching/displaying:
/**
* #Route("/admin/app", name="appTourOverview")
*/
public function appTourOverviewAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
/* Get Network for User */
$network = $this->getUser()->getNetwork();
$tours = $em->getRepository('AppBundle:Tour')->toursTodayByNetwork($network);
return $this->render(':app:index.html.twig', array(
'tour' => $tours,
'imagePath' => Constants::IMAGE_PATH_DEV,
'imagePathGreen' => Constants::IMAGE_PATH_DEV_GREEN,
'imagePathYear' => Constants::IMAGE_PATH_DEV_YEAR,
));
}
and this is how I redirected from the "database route":
return $this->redirectToRoute('appTourOverview', array(), 301); but this gets cached and the database entries are never created...
I tried:
I copied everything from the "display route" and let it return the database stuff immediately.
/* Get Network for User */
$network = $this->getUser()->getNetwork()->getId();
$tours = $em->getRepository('AppBundle:Tour')->toursTodayByNetwork($network);
return $this->render(':checker:index.html.twig', array(
'tour' => $tours,
'imagePath' => Constants::IMAGE_PATH_DEV,
'imagePathGreen' => Constants::IMAGE_PATH_DEV_GREEN,
'imagePathYear' => Constants::IMAGE_PATH_DEV_YEAR,
));
instead of the redirect. Unfortunately this only works after a refresh? ($tours is empty the first time)
Any ideas?
the 301 redirect means he page was moved permanently and this information will be cached in your browser now. Please change that parameter to 302 or just remove (this is not necessary). Then, unfortunately you need to remove your browser's cache and the it should work.
302 means the redirect is temporary and browser won't cache it;
Related
I have the following two settings page routes one for normal settings and the other for secured and admin related settings which uses the same middleware "password.confirm"
Route::get('/admin/settings',WebsiteInfoController::class,'edit'])->name('settings')->middleware('password.confirm');
Route::get('/settings',[WebsiteInfoController::class, edit'])->name('user.settings')->middleware('password.confirm');
This middleware redirects me to a second page where I have to enter password and then only i can get access to my intended page.
In my middleware I have the following function. I want to make an additional check if the user is intending to access the admin related settings
public function store(Request $request)
{
$this->validate($request, [
'secret_password' => ['sometimes','required'],
'password' => ['required','password:web'],
]);
if(redirect()->intended()->getTargetUrl()==route('settings')){
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(RouteServiceProvider::HOME);
});
});
}
Everything works fine in this method but the intended URL is lost when all the check is performed and I am redirected to homepage instead of settings page. I also tried to save the URL in a variable and use it later in the redirect command like
$path=redirect()->intended()->getTargetUrl();
if($path==route('settings')){
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended($path);
This method works fine but it also loses the URL if the second validation fails and the user is redirected back to the confirm password page. Now when I try to perform the validation second time it again loses the intended URL and redirects me back to home page.
i also tried the check with $request method.
if($request->route()->named('settings')){
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
This method however, is not able to detect the route in middleware and the validation check is not at all performed.
So, My question is how do i check for the intended URL and perform validation check without losing the intended URL even after multiple failed validation attempts?
Your method is all fine. You just used the wrong method to extract the target website URL. It is true that redirect()->intended()->getTargetUrl() gives you the target page URL but it also removes the target website URL from the session so when you finish performing the checks and want to redirect to the intended page there is no intended page URL found in the session and you get redirected to the default fall back URL. This is what the redirect function does
public function intended($default = '/', $status = 302, $headers = [], $secure = null) {
$path = $this->session->pull('url.intended', $default);
return $this->to($path, $status, $headers, $secure);
}
Here, the $request->route()->named('settings) method does not work since you are not directly interacting with your initial view but instead through a middleware view which does not send the intended page request.
Use the following code and I guess you will be all fine with your validation attempts. It will work even after multiple failed login attempts.
public function store(Request $request) {
$this->validate($request, [
'secret_password' => ['sometimes','required'],
'password' => ['required','password:web'],
]);
$path=session()->get('url.intended', RouteServiceProvider::HOME);
if($path==route('settings')) {
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended($path);
}
Today I face a strange problem (as I face this first time so it is a strange problem for me). After saving the content of a model I just write the following line of code return route('organization'); so that it will redirect to the naming route organization after saving the content.
Once the content of the organization model saves it just print the URL of the page http//xyz.laravel/organization rather than printing the content of the page itself!
When I manually type and hit the dashboard URL it surprisingly prints the dashboard URL rather than loading the dashboard content! like the below image:
Everything was working fine before I tried to store the content of that model. Once the content is stored the application starts strange behavior. Here is the code of that model:
public function store(Request $request)
{
$validated = $request->validate([
'organization_name' => 'required|unique:organizations|max:255',
'abn_number' => 'required',
'address_one' => 'required|max:100',
'state' => 'required',
'post_code' => 'required'
]);
// check organization exist or not
$org = Organization::where('organization_name', $request->organization_name)->get();
if( count( $org ) > 0 ) {
//
} else {
$organization = new Organization();
$organization->organization_name = $request->organization_name;
$organization->abn_number = $request->abn_number;
$organization->address_one = $request->address_one;
$organization->address_two = $request->address_two;
$organization->state = $request->state;
$organization->post_code = $request->post_code;
$organization->created_by = Auth::user()->id;
$organization->created_at = Carbon::now();
$organization->save();
return route('organization');
}
}
Can anyone tell me what's actually happen and how can I fix this issue?
return route('organization'); will generate the URL link to the route and print it
You can use
return redirect()->route('organization);
You can get more info from https://laravel.com/docs/8.x/redirects
This is because you are not redirecting to that route but you are returning route url as a string, to redirect a user to a named route you can use global redirect() helper as below
return redirect()->route('organization'); instead of return route('organization');
for more see
documentation
I'm looking for a PHP / Symfony code to redirect the user to another link according to his place of connection www.mondomain.fr/fr and www.mondomaine.fr/pt etc ... How can I do this ? I have included in my roads this already:
/**
* #Route("/{_locale}", name="homepage")
*
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$boutton = $em->getRepository('AppBundle:Boutton')->findAll();
$image = $em->getRepository('AppBundle:Images')->findAll();
// replace this example code with whatever you need
return $this->render('default/index.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
'boutton' => $boutton,
'images' => $image
));
}
Thank you
One of the solutions (not a PHP one) is to redirect based on browser language, you can find answer here.
You can also detect IP and redirect based on that, you can use this library to get the country/locale of the IP address and then redirect based on that.
First, let's get into the application's context:
We are on CustomerController, which is a Resource Controller sending a post request to the Store method.
This is my store method:
$customerDTO = new \repositories\dtos\CreateCustomerDTO();
$customerDTO->hydrate( Input::All() );
/** #var Customer $customer */
$customer = $this->customers->create( $customerDTO );
if ( $customer != null ){
header('Location: '.url('/customers/'.$customer->clacli));
return Redirect::action('CustomerController#show', array($customer->id) );
}
$userMessage = array(
'messageType' => 'error',
'messageContent' => 'Error creating a new Customer'
);
return Redirect::action('CustomerController#index')
->with(array('userMessage' => $userMessage));
I had to put a "header" because the Redirect call is not working.
When i put this line:
$customer = $this->customers->create( $customerDTO );
All the redirects stops to work.
And what is inside $this->customers? It's just a repository to abstract the database from the controller, i'm going to need to change the database on the near future.
Well, the code inside $this->customers->create is:
return Customer::create( $dto->toArray() );
And it's working, also all the test of my customersRepository are working. It's just a call to the Eloquent Model create method with an array of data.
So i can't figure out why the Redirect is not working. Any tip?
I tried with return 'test'; just after the call to $this->customers->create( $customerDTO); and didn't work either.
It was a strange problem with the sessions. We get it fixed, not sure why...
I checked this Cakephp cookie always get deleted automatically but, no go. That is not exactly what I've been looking for.
The cookie which Auto Login uses is getting deleted.
Here is what did:
public function login( ) {
if ($this->Auth->user('id')) {
$this->redirect(array('action' => 'dashboard'));
}
if ($this->request->is('post')) {
if($this->request->data['User']['auto_login']):
$this->AutoLogin->write($this->request->data['User']['email'],
$this->request->data['User']['password']);
endif;
if ($this->Auth->login( )) {
//$this->redirect(array('controller' => 'users', 'action' => 'edit'));
return $this->redirect($this->Auth->redirect( ));
}
else
{
$this->Session->setFlash(__('Username and Password is incorrect'), 'default', array( ), 'auth');
}
}
else {
if($this->AutoLogin->read()):
$AllData = $this->AutoLogin->read();
$AllData['username'] = 'email';
$AllData['password'] = 'password';
$check = $this->User->find('first', array('username' => 'email', 'password' => 'password'));
if($check):
$this->Auth->user($check);
$this->Auth->redirect();
endif;
$this->redirect(array('action' => 'login'));
endif;
}
It sets cookie, it does every damn thing!
But, on browser exit, it just disappears! Yes, tried with variety of browsers and also checked if browser settings is doing it.
My AppController is loading:
public $components = array('AutoLogin','Auth' => array('autoRedirect' => false), 'Cookie', 'RequestHandler', 'Session', 'Facebook.Connect' => array('model' => 'User') );//, //'DebugKit.Toolbar');
Now, here is the catch, when I check for Resources under Inspect Element, it shows me 2 things: PHPSESSID and CakeCookie[autoLogin] , PHPSESSID - type is session and expires - blank. CakeCookie type is cookie and expires after a month!
Since it 'looks' like native PHP, I thought of checking for session_start() function and I found it! It was Facebook component but, disabling it, did prevent PHPSESSID from coming but , still cookie would get deleted on browser exit.
Please advice.
Thanks in advance.
Open Facebook.php file in Facebook plugin files.
On line 4 or 5, under __construct, comment out the line which says session_start();
Ideally, CakePHP loads all the plugins which results in PHPSESSID getting set. Comment this out and even Facebook will effectively work.
Also, make sure that you create a folder called 'sessions' under your tmp folder and mark it chmod -R 0777 sessions/ , refresh your application.