trying to assign one route to more than one middleware - laravel

Please have been having issue assigning one route to more than one middleware
this is what i have in the web.php
Route::group(['middleware' => ['hodAndProvost']], function () {
Route::match(['post','get'],'applied', 'LeavesController#applied');
Route::match(['post','get'],'approval/{id}', 'LeavesController#approval');
});
this is what i have in my App\htpp\kanel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'hodAndProvost' => [
\App\Http\Middleware\hodMiddleware::class,
\App\Http\Middleware\provostMiddleware::class,
],
'application' => [
\App\Http\Middleware\hodMiddleware::class,
\App\Http\Middleware\provostMiddleware::class,
\App\Http\Middleware\lecturerMiddleware::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
this is what i have in my hodMiddleware
public function handle($request, Closure $next)
{
if ($request->user() && $request->user()->user_access_id != '2')
{
return new Response(view('unauthorized')->with('role', 'HOD'));
}
return $next($request);
}
This is what i have in my provostMiddleware
public function handle($request, Closure $next)
{
if ($request->user() && $request->user()->user_access_id != '3')
{
return new Response(view('unauthorized')->with('role', 'PROVOST'));
}
return $next($request);
}
and this is the error i get
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'App\Http\Middleware\Response' not found

You didn't import the Response class, hence why it is looking for it in the same namespace. You also don't even need to create a new Response, view() is also a response.
Try the below code:
<?php
namespace App\Http\Middleware;
use Closure;
class hodMiddleware
{
public function handle($request, Closure $next)
{
if ($request->user() && $request->user()->user_access_id != 2) {
return view('unauthorized')->with('role', 'HOD'); // like your example
// OR: //
return redirect()->back();
}
return $next($request);
}
}
Off topic but, always start your class names with a capital letter. :)

Related

change database connection just for 1 user

I need to use another db connection just for 1 user.
First of all I created another connection in the config/database.php file:
'mysqltest' => [
'driver' => 'mysql',
//...
],
It works. I tried it with something like this Model::on('mysqltest')->all().
Now I would like to change connection everywhere in the project, so I thought to change it after user login.
I'm trying this without success:
protected function authenticated(Request $request, $user)
{
//
if ($user->user_id == 1) {
//DB::purge('mysqltest');
//DB::reconnect('mysqltest');
DB::setDefaultConnection('mysqltest');
}
}
Create middleware for example
php artisan make:middleware SelectDB
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SelectDB
{
public function handle(Request $request, Closure $next)
{
if (auth()->id() == 1) {
DB::setDefaultConnection('mysqltest');
}
return $next($request);
}
}
Add middleware in App\Http\Kernel
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\SelectDB::class,
\App\Http\Middleware\EncryptCookies::class,
...

Call to a member function named() on null in laravel 5.7

I have this route
Route::get('/books/science', 'BookController#science')->name('scientific');
When I wanted to check this condition (according to document: Inspecting The Current Route)
public function handle($request, Closure $next)
{
if ($request->route()->named('scientific')) {
//
}
return $next($request);
}
I got this error. Also when I add "Route"
use Illuminate\Support\Facades\Route;
and dump these codes
dd(Route::currentRouteName());
dd(\Request::route());
I get null
$request->route() will return null in Global Middlewares.
Add your middleware in a different group as
protected $middlewareGroups = [
'web' => [
...
YOUR_MIDDLEWARE::class,
]
]
or add it in $routeMiddleware.
protected $routeMiddleware = [
...
'your_middleware' => YOUR_MIDDLEWARE::class,
];
and apply it to your route,
Route::middleware('your_middleware')->group(function () {
Route::get('/books/science', 'BookController#science')->name('scientific');
});

Laravel - How can I restrict access to admin login page based on IP address in LARAVEL?

How can I restrict access to admin login page based on IP address in LARAVEL?
I want to set a permission to the admin login page to a single IP Address.
you can use Request::ip(); and check it in middleware.. below is basic poc
middleware
class AdminAccessCheck
{
public function handle($request, Closure $next)
{
$ip = $request->ip();
if ($ip === config('admin.ip')) {
return $next($request);
}
return response()->error();
}
}
kernel.php
protected $routeMiddleware = [
...
'admin.ip_check' => \App\Http\Middleware\AdminAccessCheck::class,
];
web.php
Route::middleware(['admin.ip_check'])->group(function() {
//
});
If you prefer package, you can checkout this repo .. Firewall
Create a middleware
php artisan make:middleware IpMiddleware
Code:
<?php
namespace App\Http\Middleware;
use Closure;
class IpMiddleware
{
public function handle($request, Closure $next)
{
if ($request->ip() != "192.168.0.155") {
// here instead of checking a single ip address we can do collection of ips
//address in constant file and check with in_array function
return redirect('home');
}
return $next($request);
}
}
Register the Middleware in app/Http/Kernel.php file
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'ipcheck' => \App\Http\Middleware\IpMiddleware::class,
];
then apply middelware to routes
Route::get('/', ['middleware' => ['ipcheck'], function () {
// your routes here
}]);

Laravel Route::group for Admins

I would like to authentificate some routes, if the user is admin.
Route::get( '/user/{data}', 'UserController#getData' );
Route::post( '/user/{data}', 'UserController#postData' );
Now, I made it inside the Controller:
public function getData( $data = 'one' )
{
if ( Auth::user()->permission == 'admin' ) {
//...
} else {
//...
}
}
public function postData( Request $request, $data = 'one' )
{
if ( Auth::user()->permission == 'admin' ) {
//...
} else {
//...
}
}
I would like to make it with Route::group, but how can I do that in the routes.php?
You can create middleware which will check if user is an admin:
class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}
return redirect()->route('some.route'); // If user is not an admin.
}
}
Register it in Kernel.php:
protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
And then apply it to a route group:
Route::group(['middleware' => 'is.admin'], function () {
Route::get('/user/{data}', 'UserController#getData');
Route::post('/user/{data}', 'UserController#postData');
});
You can specify a routes group and give it a middleware
https://laravel.com/docs/5.3/routing#route-groups
https://laravel.com/docs/5.3/middleware
https://laravel.com/docs/5.3/middleware#assigning-middleware-to-routes
Example:
routes.php
Route::group(['middleware' => 'admin'], function () {
Route::get( '/user/{data}', 'UserController#getData' );
Route::post( '/user/{data}', 'UserController#postData' );
});
app/Http/Middleware/admin.php
<?php
namespace App\Http\Middleware;
use Closure;
class Admin
{
public function handle($request, Closure $next)
{
if ( Auth::user()->permission !== 'admin' ) {
//
} else {
//
}
}
}

Localization without route prefix doesn't work

I'm using the Laravel docs to implement localization (without the prefix in the url).
Basically I want two links "EN" and "NL". Depending on which link I click, the locale should be changed to that specific language.
I use this links:
NL
EN
This route:
Route::get('language/{locale}', 'HomeController#setLang');
And this is my HomeController:
class HomeController extends Controller
{
public function setLang($locale){
App::setLocale($locale);
return back();
}
}
I set my files in resources/lang the way it's explained in the docs.
But, the output ( {{ trans('messages.welcome') }} ) isn't translated.
What am I doing wrong? :)
UPDATE
{{ trans('header.register') }}
Routes
Route::group(['middleware' => ['language']], function () {
//
Route::get('language/{locale}', 'HomeController#setLang');
});
Lang file:
return [
'register' => 'REGISTREER',
];
My Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'language' => \App\Http\Middleware\Language::class,
];
If you don't want to prefix the urls, you could use the session in conjunction with a middleware.
All you need is a controller and a middleware.
App\Http\Controllers\HomeController method:
class HomeController extends Controller
{
public function setLang($locale)
{
// 1. store selected locale
Session::put('my_project.locale', $locale);
return back();
}
}
App\Http\LocaleMiddleware method:
class LocaleMiddleware
{
public function handle($request, Closure $next)
{
$default = config('app.locale');
// 2. retrieve selected locale if exist (otherwise return the default)
$locale = Session::get('my_project.locale', $default);
// 3. set the locale
App::setLocale($locale);
return $next($request);
}
}
Do not forget to register the middleware globally.

Resources