I have the following lines in my routes/api.php
Route::middleware('api')->get('/posts', function (Request $request) {
Route::resource('posts','ApiControllers\PostsApiController');
});
When I hit http://localhost:8000/api/posts it comes back blank, but when I move the above route to routes/web.php like so:
Route::group(['prefix' => 'api/v1'],function(){
Route::resource('posts','ApiControllers\PostsApiController');
});
it works.
As a reminder I have cleared the routes cache file with php artisan route:clear and my route list comes with php artisan route:list when my routes/web.php is empty and routes/api.php has the above route:
Domain
Method
URI
Name
Action
Middleware
GET|HEAD
api/posts
Closure
api
Note that with web routes part the list comes ok and works fine.
What am I doing wrong here?
Dont use the middleware api and see following route example for API routes
Example 1 (in your api.php)
Route::get('test',function(){
return response([1,2,3,4],200);
});
visit this route as
localhost/api/test
Example 2 (if you want api authentication, token based auth using laravel passport)
Route::get('user', function (Request $request) {
///// controller
})->middleware('auth:api');
You can make get request for this route but you need to pass the access token because auth:api middleware has been used.
Note: see /app/http/kernel.php
and you can find the
protected $routeMiddleware = [
//available route middlewares
]
There must not be such (api) kind of middle ware in this file (kernel.php) for routes unless you create one, that why you can not use middleware as api.
Here, How I am creating REST APIs (api.php)
//All routes goes outside of this route group which does not require authentication
Route::get('test',function(){
return response([1,2,3,4],200);
});
//following Which require authentication ................
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function(){
Route::get('user-list',"Api\ApiController#getUserList");
Route::post('send-fax', [
'uses'=>'api\ApiController#sendFax',
'as'=>'send-fax'
]);
Route::post('user/change-password', [
'uses'=>'api\ApiController#changePassword',
'as'=>'user/change-password'
]);
});
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.
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.
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.
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