I have middleware that redirects the user if it it not logged in. The user is not prevented from filling in the form, only when he submits the data my middleware comes in to check if he is authenticated. It seems like it is not passing throught the middleware at all when the submit button is clicked.
My route
Route::group(['middleware' => 'allow.access'], function(){
Route::post('houses', [ //I wonder if I defined this
'as' => 'houses.store', //route correctly because
'uses' => 'HousesController#store' //it seems Laravel is ignoring it
]);
Route::get('houses/{id}/edit', [
'as' => 'houses.edit',
'uses' => 'HousesController#edit'
]);
});
My middleware works if I use this route inside the group:
Route::get('houses/create/{zip}', [
'as' => 'houses.create',
'uses' => 'HousesController#create'
]);
my middleware
public function handle($request, Closure $next)
{
if(!$request->session()->has('loginInfo'))
{
return redirect()->route('register.login');
}
return $next($request);
}
Related
I'm learning laravel and I have a problem with my base url which is http://localhost/.
It keeps redirecting to http://localhost/home which is the base authentication route and since im not logged in, it redirects me to http://localhost/login.
I want http://localhost/ to redirect to http://localhost/blog/posts as it should.
I'm doing this because in the future the base url will redirect to another page. Until then, I want to display the blog posts.
web.php
Route::get('/', [
'as' => 'index',
'uses' => 'HomeController#index',
]);
Route::get('/blog/posts', [
'as' => 'blog',
'uses' => 'BlogController#index'
]);
Auth::routes();
Route::get('/home', [
'as' => 'home',
'uses' => 'HomeController#home'
]);
HomeController.php
public function home()
{
return view('home');
}
public function index()
{
return view('blog');
}
I hope I was clear enough, i'd be glad to give more info if needed.
Problem solved:
Comment or remove $this->middleware('auth'); in HomeController.php and add it in the route:
Route::get('/home', [
'as' => 'home',
'uses' => 'HomeController#home'
])->middleware('auth');
Check that the HomeController __construct() function doesn't have an auth middleware inside, that would try to log you in first, then continue to check for the index function.
I use Laravel 5.6.33. I would like the user can have an access to the 'dashboard' page only when he/she has signed In/Up. When I use the 'guest' middleware, the user can't access the page at all and when I use the 'auth' middleware, the user always have an access to the page. What shall I do?
Route::group(['middleware' => ['web']], function (){
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
});
I have also added $this->middleware('auth'); in the getDashboard function or in the constructor of the UserController but it doesn't work. What shall I do?
In the Kernel.php the auth address is as follows:
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
If you are using Laravel 5.6 you don't need to wrap your routes with web middleware as long as you put them inside your routes\web.php file. Laravel makes this for you in the RouteServiceProvider.php.
For your purpose the auth middleware should work. Try this instead of what you have:
Route::middleware('auth')->group(function() {
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard'
]);
});
you have to do nothing.
just add the following code.
Route::group(['middleware'=>'auth'],function () {
//you can create the list of the url or the resource here to block the unath users.
Route::resource('brands', 'BrandController');
Route::resource('products', 'ProductController');
});
Or use the construct function on the controller which you want to block.
public function __construct()
{
$this->middleware('auth');
}
it will block all the function on that controller like index, create, store, update, delete. only auth can use those functions.
just some weeks ago I started with Laravel and I made some good progress in these weeks with my project.
3 days ago I decided to implement some roles for my users in the system.
I created a middleware via artisan and wrote the code for it.
The problem I have is to assign my middleware to a specific route.
First I added this line to the $routeMiddleware-array in the Kernel.php: 'role' => \App\Http\Middleware\RolesMiddleware::class,.
my routes/web.php-file looks like this on:
// Member area
Route::group(['prefix' => 'member', 'middleware' => ['auth', 'role']], function() {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => function () {
return view('member.dashboard');
}]);
Route::group(['prefix' => 'user'], function() {
Route::get('showUsers',[
'uses' => 'UserController#showUsers',
'as' => 'manageUsers',
'roles' => 'manageUsers'
]);
});
});
First I had only the 'auth' middleware in the first group and I wanted to add my 'role' middleware as additional action directly on my get-route like middleware => 'role:manageUsers'. In this case my middleware was ignored totally and did not get called in any case.
After is put the middleware in the array like in the code above it got called at least.
Now I tried to add a custom action 'roles' with the value 'managerUsers' to my get-route. The middleware still gets called and if output the actions via var_dump(request->route()->getAction()); I see the actions 'uses' and 'as' but not my custom action 'roles'.
I have srsly no clue whats wrong. Does anyone know if it isn't possible to add custom actions or an additional middleware to a specific route?
Best regards.
EDIT 1 (17.07.2017)
My \app\Http\Middleware\RolesMiddleware.php looks like this:
namespace App\Http\Middleware;
use Closure;
class RolesMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param \string[] ...$roles
* #return mixed
*/
public function handle($request, Closure $next, string ...$roles)
{
var_dump($roles);
die('middleware reachted');
}
}
My \app\Http\Kernel.php looks like this:
...
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'role' => \App\Http\Middleware\RolesMiddleware::class,
];
...
And my \routes\web.php look like this:
...
Route::group(['prefix' => 'member', 'middleware' => ['auth', 'role']], function() {
...
Route::group(['prefix' => 'user'], function() {
Route::get('showUsers',[
'uses' => 'UserController#showUsers',
'as' => 'manageUsers'
]);
});
});
...
If I do assign my middleware as an array together with the "auth" middleware, my one will be called. The point is, that I want to define a role the user has to have with a specific route. (In this case with the Route::get(...))
If I do assign my middleware not together with the "auth" middleware (e.g. in the group with prefix "user"), it will be totally ignored. The same if I do assign my middleware with the get-route directly.
Route::group(['prefix'=>'user', 'middleware'=>'role:manageUsers'], function() {
Route::get('/showUsers',[
'uses' => 'UserController#showUsers',
'as' => 'manageUsers'
]);
});
Your RolesMiddleware.php:
class RolesMiddleware{
public function handle($request, Closure $next, ...$roles){
// sent arguments are stored in $roles array
print_r($roles); // Array ( [0] => manageUsers )
}
}
Have you registered your middleware in your kernel.php?
Best regards...
As usual the problem was in front of the PC.
I copied some more routes for later usage and forgot to change the value for 'as' in the action-array.
Because I'm using the value of the 'as' key for my template to find the correct page I got redirected by another route than expected. Sadly this one pointed to the same controller and action and I didn't noticed the wrong URL in my browsers adress bar.
My role-middleware worked as expected but I just accessed the wrong page.
I have a controller UserController.php which contains the following methods:
getIndex(), getAll(), getCreate(), postStore(), getShow(), getEdit(), putUpdate(), getDestroy(), getLogin(), getDashboard(), and getLogout().
I have included the following codes into the routes.php
Route::get('/', function()
{
return View::make('hello');
});
Route::get('users/all/', [ 'as' => 'users.index', 'uses' => 'UserController#getAll']);
Route::get('users/create/', [ 'as' => 'users.getCreate', 'uses' => 'UserController#getCreate']);
Route::get('users/{all}/edit', 'UserController#getEdit');
Route::put('users/update/{id}', [ 'as' => 'users.putUpdate', 'uses' => 'UserController#putUpdate']);
Route::controller('users', 'UserController');
I can access the pages like
http://localhost/testlaravell/users/
or
http://localhost/testlaravell/users/add
etc.
Now, I want that only logged in users can access the pages, other wise s/he will be redirect to the login page http://localhost/testlaravell/login
The methods for login under UserController.php as follows:
public function postSignin() {
$rules = array(
'username' => 'required', // make sure the username is an actual username
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('users/login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata)) {
return Redirect::to('users/dashboard')->with('message', 'Welcome User');
} else {
// validation not successful, send back to form
return Redirect::to('users/login')->with('message', 'Sorry!! Username/ Password seems wrong.');
}
}
}
public function getLogin() {
return View::make('users.login');
}
You'll want to make use of the Auth Filter in Laravel 4
You can wrap all your routes in a group and specify that filter, in your case the code would be something like this.
Route::group(array('before' => 'auth'), function()
{
Route::get('users/all/', [ 'as' => 'users.index', 'uses' => 'UserController#getAll']);
Route::get('users/create/', [ 'as' => 'users.getCreate', 'uses' => 'UserController#getCreate']);
Route::get('users/{all}/edit', 'UserController#getEdit');
Route::put('users/update/{id}', [ 'as' => 'users.putUpdate', 'uses' => 'UserController#putUpdate']);
Route::controller('users', 'UserController');
});
You can checkout the documentation on Route Groups here
so I have to make this system for transport management. The user can log in create/update/edit all his trips. But the admin can do the same for all users. I have divided user and admin in to route prefixes:
Route::group(['prefix' => 'admin/', 'middleware' => ['auth','admin']], function(){
Route::resource('trips', 'TripsController',
array('except' => array('show')));}
Route::group(['prefix' => 'user/', 'middleware' => ['auth', 'user']], function(){
Route::resource('trips', 'TripsController',
array('except' => array('show')));
}
The problem is in every method of the TripController I have to pass route variable with the correct url (the admin request will have a 'admin' prefix, and the users will have 'user' prefix)
return View('trips.index', compact('users', 'route'));
The question is there a way to do this nicely or should I just pull the trips Route::resource out of the both groups so that it wouldn't have any groups? What is the correct approach here?
I use this approach:
Route::group(['namespace' => 'Admin', 'as' => 'admin::', 'prefix' => 'admin'], function() {
// For Other middlewares
Route::group(['middleware' => 'IsNotAuthenticated'], function(){
// "admin::login"
// http://localhost:8000/admin/login
Route::get('login', ['as' => 'login', 'uses' => 'AdminController#index']);
});
// For admin middlewares
Route::group(['middleware' => 'admin'], function(){
// "admin::admin.area.index"
// http://localhost:8000/admin/area/{area}
Route::resource('Area', 'AreaController');
// "admin::dashboard"
// http://localhost:8000/admin/
Route::get('/', ['as' => 'dashboard', 'uses' => 'AdminController#dashboard']);
});
});
Whenever I need to access url in blade templates I simply use route helper method.
// For resourceful routes
{{ route('admin::admin.city.index') }}
or
//For regular get/post routes
{{ route('admin::dashboard') }}
Or simply run artisan command to list route names.
php artisan route:list
I did it with this:
//Admin Group&NameSpace
Route::namespace('Admin')->prefix('admin')->group(function () {
Route::get('/dashboard', 'DashboardController#index')->name('dashboard')->middleware('auth');
});
Even you can customize the ->middleware('auth'); with a custom middleware role based.