I want to make the access to /Inscription in my website unavalible untill the admin gives access to it in the /admin page soo when the guest goes to /inscription he gets a message "unavalible" untill the admin goes to /admin and unlock it
i tried to make it using the middleware on laravel but i doesn't seem the work .
i did php artisan make:middleware Access
and coded and made a view unavalible i want it to load when he goes to /Inscription
kernel.php :
protected $middleware = [
.....
\App\Http\Middleware\Access::class,
];
protected $routeMiddleware = [
'access' => \App\Http\Middleware\Access::class,
the access middleware :
<?php
namespace App\Http\Middleware;
use Closure;
class Access
{
public function handle($request, Closure $next)
{
echo "mwajer";
return $next($request);
}
}
Route::group(['middleware' =>['access']], function (){
Route::get('/inscription', MyInscriptionController#index)->name('inscription');
//All your routes that you needs admin approval here
});
Put all your restricted route inside the group, also it is a good idea to use route naming. You can add multiple middleware to the group
Related
I just started my first Laravel project and try to combine Jetstream Authentification with Voyager Admin Panel.
First of all, I installed Jetstream on a fresh Laravel installation and it worked so far:
Afterwards, I tried to add Voyager to generate the CRUDs for my website and added a new user with
php artisan voyager:admin your#email.com --create
But whenever I tried to login through the url "../admin", I was redirected to "../dashboard" from Jetstream.
Even if I reentered "../admin" as URL, I was redirected. As long as I was logged in, I cannot enter the Voyager Backend.
So I guess it's some kind of routing / middleware issue, but I cannot find out which issue it is.
Within the web.php Routing file, there's only the basic stuff:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
});
Not sure if that's relevant, but my IDE recognizes Voyager:: as unknown class, even it works the same way on a different Laravel installation.
But from the look of it, I expected the Route::middleware() to redirect a logged in person which types the url "../dashboard" to the Dashboard view, but nothing more. Removing this Route also didnt help the problem, so I guess I was wrong.
But beside this, only the pure Voyager Routes are left, so I'm not sure where else I can look to solve this problem.
You can add custom responses on app/Http/Responses directory.
just make new responses called LoginResponse
then use this code
<?php
namespace App\Http\Responses;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
/**
* #param $request
* #return mixed
*/
public function toResponse($request)
{
$home = auth()->user()->is_admin ? '/admin' : '/dashboard';
return redirect()->intended($home);
}
}
Then, bind your LoginResponse in FortifyServiceProvider
You can use this code
<?php
namespace App\Providers;
// ...
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// ...
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
}
}
i know that it to late but for other users who had the same problem.
first i installed jetstream
int .env file APP_URL=http://localhost:8000
i installed voyager with dummy data
i added manualy in table user_roles this ligne ( the admin )
INSERT INTO `user_roles` (`user_id`, `role_id`) VALUES ('1', '1');
and it work
you can see this video i found in youtube i think it will help you .
https://www.youtube.com/watch?v=UDYZx5uIwmQ
i'm using laravel 6 and have 2 route in my app; index and dashboard.
My routes/web is:
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController#index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard#dashboard')->name('dashboard');
});
i added dashboard route recently.
Auth::user() is null when i dump it in dashboard route but doesn't in index. What's the
Your Controller is instantiated before the middleware stack has ran; this is how Laravel can know what middleware you have set via the constructor. Because of this you will not have access to the authenticated user or sessions at this point. Ex:
public function __construct()
{
$this->user = Auth::user(); // will always be null
}
If you need to assign such a variable or access this type of information you would need to use a controller middleware which will run in the stack after the StartSession middleware:
public function __construct()
{
$this->middleware(function ($request, $next) {
// this is getting executed later after the other middleware has ran
$this->user = Auth::user();
return $next($request);
});
}
When the dashboard method is called, the middleware stack has already passed the Request all the way through to the end of the stack so all the middleware needed for Auth to be functioning and available has already ran at that point which is why you have access to Auth::user() there.
I think that this has something to do with the 'web' middleware. If you take a look into the Kernel.php (In app\Http) you will find the web middleware group.
This will show you that it actually calls a middleware called StartSession. Based on your route file (where web is not included as a middleware) I would think that you don't have a session in your Controller and there for no access to it.
I don't quite understand why this only happens in your /dashboard route, because the issue should also be in your /index route (unless you added the web middleware somewhere in your TodoController).
I think that this should do the trick:
Route::middleware(['web', 'auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController#index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard#dashboard')->name('dashboard');
});
If you fire php artisan make:auth command.
It's doesn't matter where you define because of it's only define auth route
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController#index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard#dashboard')->name('dashboard');
});
Auth::routes();
I have 2 roles, which is admin and user. Now when logging in, the admin goes to the dashboard route while the user goes to home. When user is logged in and changes the url to http://127.0.0.1:8000/dashboard it can access the admin's panel and I don't want that. How can I do achieve this?
PS. I'm new to Laravel
The good practice for this is usage of Middewares.
Create middlewares for admins and users (I'll do that only for admins, you can do that similarly for users):
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
public function handle($request, Closure $next)
{
if(Auth::check()){
// check auth user role (I don't know how you can implement this for yourself, this is just for me)
if(Auth::user()->role->name == 'admin'){
return $next($request);
} else {
return redirect()->route('admin.dashboard'); // for admins
}
}
return redirect()->route('main'); // for users
}
}
In "app/Http/Kernel.php" in $routeMiddleware array register that (add to end of that array).
'Admin' => \App\Http\Middleware\AdminMiddleware::class,
Now if you are using all requests in "routes/web.php" (actually I think it does), then you can use routes like this for admins:
// USER ROUTES
Route::get('/', 'FrontController#main')->name('main');
// ADMIN ROUTES
Route::group([
'as' => 'admin.',
'middleware' => [ 'Admin' ],
], function () {
Route::get('dashboard', 'AdminController#dashboard');
});
Refresh caches via "php artisan config:cache".
Try it!
Use middleware to admin route or inside the controller
like this:
Route::put('post/{id}', function ($id) {
//
})->middleware('role:editor');
or
Route::middleware(['auth', 'admin'])->group(function (){
Route::get('dashboard', 'HomeController#index')->name('home.index');
});
or inside the controller like this:
public function __construct()
{
$this->middleware(['auth', 'admin'])->except(['index']);
}
or you can use this for middleware roles.
I've been trying for some time to figure this out, but no solution I found was conclusive. Basically I'm trying to retrieve a list of clients based on the user logged in, but I cannot retrieve the user object anywhere in the controller except the index() function where is returns the view, and also the blade template that displays the logged in user's name.
This is my ClientController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Models\Client;
use App\Http\Requests\GetClientsRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class ClientController extends Controller
{
protected $user;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
/**
* Show the clients page.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
Log::info("client user: " . print_r($this->user, 1));
return view('page');
}
public function getClients()
{
$currentUser = Auth::user();
if ($currentUser) {
$clients = Client::with('account')
->where('user_id', $currentUser->account)
->get();
$collection = collect($clients);
return response($collection->toArray());
}
}
}
The Log in the index function prints out the user object no problem - but when it's called in the getClients() function, it's empty. I also tried using this in the __construct():
$this->middleware('auth');
As per the Laravel template I was using, but whenever I call the getClients API route I always get a 401 Unauthorized error.
Here is my api.php routes file (although only currently using the getClients call) :
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('welcome-message', 'DashboardController#getWelcomeMessage');
Route::prefix('clients')->group(function () {
Route::get('/', 'ClientController#getClients');
Route::get('/{clientId}', 'ClientController#getClient');
Route::post('/', 'ClientController#postCreateClient');
Route::put('/{clientId}', 'ClientController#putUpdateClient');
});
And my web.php routes file:
<?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/', 'HomeController#index')->name('dashboard');
Route::get('/clients', 'ClientController#index')->name('clients');
The system knows I'm logged in, because I wouldn't even be able to visit the client dashboard at all, so I don't understand why I cannot get a result from Auth::user() in the function - unless I'm using the middleware incorrectly?
You will have to use the auth:api middleware to allow API authentication.
To do so, add this middleware to your API route, omit in that case to add middleware in the __constructor.
Route::group([
'prefix' => 'clients',
'middleware' => ['auth:api']
], function(){
Route::get('/', 'ClientController#getClients');
// ... etc
});
Make sure that you have a valid access token to access your API. When using your API with a JS front-end, read about it in the Laravel docs.
Note that 'web' authentication (middleware: auth) uses a different mechanism than API authentication (middleware: auth:api) to authenticate users.
I have MUltiple login in laravel 5 with using differeent different controller like that Account controller and Admin controller . i want to use Middleware on route for authorize the user. what can i do ?
Step 1: Create the AdminLoggedInMiddleware
php artisan make:middleware AdminLoggedInMiddleware
Step 2: Register AdminLoggedInMiddleware in app\Http\Kernel.php in the protected $routeMiddleware array.
protected $routeMiddleware = [
...,
'admin' => 'App\Http\Middleware\AdminLoggedInMiddleware',
];
Step 3: Check if Admin is logged in, so, open AdminLoggedInMiddleware and replace the default handle method with this:
public function handle($request, Closure $next)
{
// Change this condition as per your requirement.
if ( Auth::check() && Auth::user()->role === 'administrator' ) {
return $next($request);
}
return redirect()->back();
}
Step 4: Open your AdminController.php file and add the following method:
public function __construct()
{
$this->middleware('admin');
}
Similarly, you can create the other middleware for your other user(s) and check if they are logged in or not.