laravel routing issue with domain - php

I am using laravel version 5.1. I have been using domain routing functionality and have had success with the following code as described in the docs. But the problem is that, When the user visits user.mysite.com, it is taking too much time to load routes.
Below is my route:
Route::group(['domain' => 'user.mysite.com'], function () {
Route::resource('users', 'UserController', ['except' => ['edit', 'create', 'destroy']]);
});
As, shown below in the image you can see the time difference it is taking to load routes after loading autoload file.
image for time difference with domain routes
When i do the same thing with prefix instead of domain routes it loads easily without taking time.
Route::group(['prefix' => 'user')], function () {
Route::resource('users', 'UserController', ['except' => ['edit', 'create', 'destroy']]);
});
image for time difference with prefix routes
Laravel version is 5.1, Using Apache 2.4.23, and PHP version 5.6.25.
I want to know, Why it is taking this much time, and what is the solution for this.

Related

Laravel route conflict with resource routes

I'm using this route in a project hosted in my local mac pc, it is working, but when i have uploaded that to an Ubunto server route conflict occurred.
Route::group(['prefix'=>'report', 'middleware' => ['auth','session', 'complete_profile']], function() {
Route::get('/get_query', 'ReportController#get_queries');
});
Route::group(['middleware' => ['auth','session', 'complete_profile']], function(){
Route::resource('report','ReportController');
});
for example when i use form first route report/get_query in online ubunto server it goes to the show($id) method of that controller, But in local its working.
What should I do with this ?
Route::group(['prefix'=>'report', 'middleware' => ['auth','session', 'complete_profile']], function() {
Route::resource('/','ReportController',['except' => ['show']]);
Route::get('/get_query', 'ReportController#get_queries');
});
Resource route has predefined route for http methodes. For example reporte resource has route:
Route::get('report/{report}','ReportController#show');
Solution is to exclude some methodes (routes from restfull resource), or to make some routes that wont conflict with route resource.
You can see what route you have registered by running:
php artisan route:list
Also one route group for report is enough just put '/' in resource route.

Laravel unexpected redirects ( 302 )

I have started a new Laravel 5.2 project, using laravel new MyApp, and added authentication via php artisan make:auth. This is intended to be a members only website, where the first user is seeded, and creates the rest (no manual user creation/password reset/etc).
These are the routes I have currently defined:
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::get( 'user/login', ['as' => 'user.login', 'uses' => 'Auth\AuthController#showLoginForm']);
Route::post('user/login', ['as' => 'user.doLogin', 'uses' => 'Auth\AuthController#login' ]);
Route::group(['middleware' => 'auth'], function() {
// Authenticated user routes
Route::get( '/', ['as'=>'home', 'uses'=> 'HomeController#index']);
Route::get( 'user/{uid?}', ['as' => 'user.profile', 'uses' => 'Auth\AuthController#profile' ]);
Route::get( 'user/logout', ['as' => 'user.logout', 'uses' => 'Auth\AuthController#logout' ]);
Route::get( '/user/add', ['as' => 'user.add', 'uses' => 'Auth\AuthController#showAddUser']);
[...]
});
});
I can login just fine, however I'm experiencing some very "funky" behavior - when I try to logout ( via the built-in logout method that was created via artisan ), the page does a 302 redirect to home, and I am still logged in.
What's more, while almost all pages (not listed here) work as expected, user.add also produces a 302 to the home page.
Do note the homepage is declared to the AuthController as $redirectTo, if that makes any difference
I found out about the redirects via the debugbar. Any idea on what to look for ?
I got the same issue and i solved it by adding the header with accept:'application/json'. And I think I checked the source code before which indicates that if you don't add this, it might redirect when you are using the auth middleware. But I am not sure if it is the case and I cannot recall where i found this.
After several hours of hair pulling, I have found my answer -- and it's silly.
The problem is that the route user.profile has a path user/{uid?} and it matches both user/logout and user/add as paths.
It being before the others, and not having a regex or similar, it handled the route.
I still don't know why a 302 was generated for that page, but found that moving it out of the AuthController and into the UserController (where it should be from the start) fixed the behavior.
Thus, my (amended and working) routes now look like so:
Route::group(['middleware' => 'web'], function () {
// Authentication Routes...
Route::get( 'user/login', ['as' => 'user.login', 'uses' => 'Auth\AuthController#showLoginForm']);
Route::post('user/login', ['as' => 'user.doLogin', 'uses' => 'Auth\AuthController#login' ]);
Route::group(['middleware' => 'auth'], function() {
// Authenticated user routes
Route::get( '/', ['as'=>'home', 'uses'=> 'HomeController#index']);
Route::get( '/home', ['as'=>'home', 'uses'=> 'HomeController#home']);
Route::get( 'user/logout', ['as' => 'user.logout', 'uses' => 'Auth\AuthController#logout' ]);
// *** Added /profile/ here to prevent matching with other routes ****
Route::get( 'user/profile/{uid?}', ['as' => 'user.profile', 'uses' => 'UserController#profile' ]);
Route::get( '/user/add', ['as' => 'user.add', 'uses' => 'UserController#showAddUser']);
[...]
});
});
I encountered an issue with 302 Redirects when posting ajax requests. The solution in this case was to remember to include the CSRF token.
See the Laravel 5.4 documents here: https://laravel.com/docs/5.4/csrf
For me it was guest middleware!
This middleware redirects user to homepage if authenticated.
You don't have to use it for Api requests. So I removed it and the problem solved.
May be default redirect page after logout is home and seems like you do not have home in your web route. Try the below code in your AuthController.php
use AuthenticatesAndRegistersUsers, ThrottlesLogins; // after this line
$redirectAfterLogout = 'login' // add this line
This will redirect you to login page after logout. You can change it to any route if you wish. I used login as an example.
OR
You can change after logout route in \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
public function logout()
{
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : 'login');
}
I changed the default route to login. If you don't have $redirectAfterLogout in your AuthController.php it will look here for redirect path. I don't suggest people to edit here, it's kind of hard coding.
I had this issue and it turned out I had a route:redirect inside my ajax controller.
which doesn't make sense because obviously we have to return ajax but I was returning a route!
I too experienced this issue in the login page which worked fine previously. So thought have a look at the directory permissions and it resulted the following:
drwxr-xr-x 7 user user 4096 Jun 27 2019 storage
So storage directory has 755 permission which means only the owner has write access, Since that directory owned by "user" others like laravel can't write into it.
Changing the directory to 777 with this cmd resolved my issue:
sudo chmod 777 -R PROJECT_PATH/storage
The right way,
Since making that directory world-writable isn't the right way, make that directory owned by apache and set 775 to storage.. and it worked again.
sudo chown -R user:www-data PROJECT_PATH/storage
sudo chmod 775 -R PROJECT_PATH/storage
I use a lot ajax (get & post) and with every response I update the token with session()->regenerate() on the server, then on the client side I update every token field with js.
But last week, I delete by mistake the one liner function to do that. So, suddenly the system starts to give a 302 response after the second call. It was so hard to find what was going on, because it works sometimes (firstime) and sometimes don't.
After I realize it was a token mismatch, I struggle a couple of days trying to find why, because the response don't point a token mismatch, just the 302 redirect.
Finally, I find the problem by dd() both tokens on the tokensMatch() function. I don't know why it won't trigger a TokenMismatch.
I hope this anecdote help you.
If your website doesn't use HTTPS you have to define the following attribute in your .env
SESSION_SAME_SITE=Strict
Note: this precaution applied by some browsers to prevent exploit website's users
For me it was this in my controller:
public function __construct()
{
$this->middleware('admin');
}
For me it was config/session.php
I changed some values there for production app like path, secure, same_site
But on local due to http://localhost, Secure session was failing to create any cookies.
That's why Authenticate middleware redirecting to login page with status 302
I have modified my login route with adding as parameter to it and it worked for me.
Route::get('login', ['as' => 'login', 'uses' => 'loginController#index']);
As for me encountered 302 status during saving and what fixed that was inserting
Accept: application/json on ajax header, because i hava a script inside the php file.
$.ajax({
url:'{{route('fetchMunCit')}}' +'/'+id,
type:'GET',
dataType:'json',
Accept: application/json
success:function(response)
In case somebody is experiencing this.
My case was that the APP_URL value is different from the actual URL hence I was getting 302 error.

Laravel 5.1 - Overloaded routes

I have a homegrown, Laravel 5.1 base application on top of which I build specific applications. The base application uses a named route for login, naturally called "login", which listens for GET /login.
In one of my specific applications, I attempted to overload that route to send the requests to a different controller. It seemed to work for a while, but then it started going to the base application's controller again. I'm sure I changed something to break it, but the problem is that I can't figure out how to fix it again.
My base application routes are all defined in app/Http/Routes/core.php. The relevant route:
Route::get('login', [
'as' => 'login',
'uses' => '\MyVendor\Core\Http\Controllers\AuthController#getLogin'
]);
My specific application routes are defined in app/Http/Routes/app1.php. The relevant route:
Route::get('login', [
'as' => 'login',
'uses' => 'App1\AuthController#getLogin'
]);
App2 and App3 are defined similarly. My app/Http/routes.php adds these routes like this:
require 'Routes/core.php';
Route::group(['domain' => 'app1.com'], function() {
require 'Routes/app1.php';
});
Route::group(['domain' => 'app2.com', function() {
require 'Routes/app2.php';
});
Route::group(['domain' => 'app3.com', function() {
require 'Routes/app3.php';
});
The problem I am seeing is that visiting app1.com/login, app2.com/login, and app3.com/login all result in the execution of \MyVendor\Core\Http\Controllers\AuthController#getLogin rather than App1\AuthController#getLogin.
EDIT: I have changed the problem description since I was describing it incorrectly as a problem with calls to route('login').
The index of the routes in Laravel follows a "$domain$uri" format, therefore routes with a domain won't overwrite those without. A fallback route without a domain should be declared after the domain group, so it is later in the route collection and won't match before a route with a matching domain.
"the most recent definition for a route is the effective route"
This is not a bug, this is the expected behaviour, a simple example would be setting a variable to value 1 then setting it to value 2, of course the (most) recent value takes place.

Laravel Route redirecting to the right controller when using parameters [architecture]

So building a few pages on the same template and loading the content via AJAX. Most of the content are forms. Views are defined by step number (1,2,3,4,5....32)
Here is how I built my route:
Route::get('onboarding/', [
'as' => 'get-onboarding-start',
'uses' => 'OnboardingController#getStart'
]);
Route::get('onboarding/{i}', [
'as' => 'get-onboarding-step',
'uses' => 'OnboardingController#getNextStep'
]);
Route::post('onboarding/{i}', [
'as' => 'post-onboarding-step',
'uses' => 'OnboardingController#postStepForm'
]);
Now one method in the controller cannot handle all the work. Meaning I will need to redirect to another method based on the $i (step number).
I am afraid that it is not simple to read if I put a big blog of switch case $i = 1,2,3...
At the same time I don't want to write 32 different routes.
What would you propose?
Hard code all the routes meaning: 'onboarding/username' then
'onboarding/email' etc... etc... The good point is that it is super
simple to read in the views and you know exactly what the next step
is... no need to check what the number corresponds to.
Catch all as coded now and redirect to different methods in the controller
Something better, super easy to read and with little lines of
code... which is .... ??
If these steps are going to remain as they are without many changes in the future, I'd go for the first option (having 32 get & 32 post routes). This will keep your application simple, if you'd want to apply parameters or middleware to them you can use route groups. Below I've posted a small code example from the laravel documentation
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});

Laravel REST route doesn't function

I am attempting to implement the Satellizer authentication system into my Angular app. I have experience with PHP and Laravel, so I decided to use that as my backend.
Right now I am attempting to mimic what they do in their example Laravel code. That can be found here: https://github.com/sahat/satellizer/tree/master/examples/server/php.
I have installed Xdebug on my server and have it successfully connecting with my PHPStorm. Here is what my routes.php looks like.
// OAuth, Login and Signup Routes.
Route::post('/api/auth/facebook', 'AuthController#facebook');
Route::post('/auth/twitter', 'AuthController#twitter');
Route::get('/auth/unlink/{provider}', ['middleware' => 'auth', 'uses' => 'AuthController#unlink']);
// API Routes.
Route::get('/api/me', ['middleware' => 'auth', 'uses' => 'UserController#getUser']);
Route::put('/api/me', ['middleware' => 'auth', 'uses' => 'UserController#updateUser']);
// Initialize Angular.js App Route.
Route::get('/', 'HomeController#index');
On my sign in page, I have an authentication button for Facebook. After the Facebook popup appears, I have it calling back to my Laravel. In the JavaScript console it shows that it is attempting to contact the correct route. Heres what it prints.
POST http://localhost:8888/api/auth/facebook 404 (Not Found)
I have the following method inside AuthController.php.
/**
* Login with Facebook.
*/
public function facebook(Request $request) {...}
The function is never hit. From the information printed in the console, it appears that it doesn't know it exists at all. Is there something I am doing wrong?
The route Route::get('/', 'HomeController#index'); is hit upon every request, and it goes inside HomeController and hits the index method every time.
But

Categories