Just migrated my Laravel app from a local environment to a online development environment on a remote server. After this migration I am getting an error:
ReflectionException thrown with message "Class App\Http\MiddleWare\NotUser does not exist"
I've deleted the vendor folder, as well as composer.lock and ran composer update. Also cleared bootstrap/cache and also tried runningphp artisan config:clear.
Purged all cache/* files from storage. Whenever I attempt to log in to the dashboard, I receive the error that middleware does not exist.
app/Http/Middleware/NotUser.php
<?php
namespace App\Http\Middleware;
use Closure;
class NotUser
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
# This middleware prevents anyone who is not an admin from accessing given route or controller
# apply by using it in the constructor, $this->middleware('is.admin');
if ($request->user()->role->name === 'user') {
return back()->with('error', __('Access denied'));
}
return $next($request);
}
}
app/Http/Kernel.php
protected $routeMiddleware = [
...
'not.user' => \App\Http\MiddleWare\NotUser::class
];
routes/web.php
Route::group(['prefix' => 'admin', 'middleware' => ['not.user', 'auth']], function () { ... }
This works fine on locally hosted environment. I had no problems. After I switched to a development environment I started receiving this error and I have no idea what's causing this.
The namespace is case sensitive I believe, so change this:
protected $routeMiddleware = [
...
'not.user' => \App\Http\MiddleWare\NotUser::class
];
to this:
protected $routeMiddleware = [
...
'not.user' => \App\Http\Middleware\NotUser::class
];
Notice the capital W in Middleware.
Related
I have created a middleware, the middleware name is expireDateCheck
This middleware class I have kept to Kernel.php and I've added to this class protected $routeMiddleware.
Inside Kernel.php code is:
protected $routeMiddleware = [ 'expireDateCheck' => \App\Http\Middleware\expireDateCheck::class, ]
Then I've given a condition inside middleware expireDateCheck.php for redirecting to the dashboard, this condition working fine but the main problem is it's redirecting to the dashboard two times which means after showing dashboard then it's showing again dashboard page it seems like dashboard page loading multiple time.
How can I fix this problem?
Inside middleware expireDateCheck.php code is:
<?php
namespace App\Http\Middleware;
use Closure;
use App\User;
use App\Client;
use Auth;
use Redirect;
class expireDateCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()){
$currentDate = date('Y-m-d H:i:s');
$userExpireDate = Client::where('expire_date', '<' , $currentDate)->first();
if($userExpireDate){
return Redirect::to('dashboard');
}
return $next($request);
}
}
}
Here are my routes:#Nikolay
Route::group(['middleware' => 'expireDateCheck'],function(){
-------------------------------
-------------------------------
});
Route::get('dashboard','DashboardController#index')->middleware('admin');
The middleware is run on all urls, therefor also on the request when loading the dashboard. You can remove the middlewares when defining the routes, this will avoid it from loading twice, and since the logic is to return them to the dashboard it does not makes sense running it on the dashboard.
Route::get('dashboard', 'DashboardController#index')->withoutMiddleware(['expireDateCheck']);
Or by grouping multiple.
Route::group([
'excluded_middleware' => ['expireDateCheck'],
], function () {});
I used to run debug true in production when needed with Laravel 5 the following way:
'debug' => env('APP_DEBUG', $_SERVER['REMOTE_ADDR'] == 'myipaddress' ? true : false),
However Laravel 6 doesn't let me use it, when I do artisan config:cache, artisan complains that:
variable $_server['REMOTE_ADDR'] is not defined and exists.
Is there another way someone has found out to be working to do this with Laravel 6?
You can't cache dynamic configs. there is no request and no $_server when Laravel tries to cache your configs.
You must disable your debug on production (APP_DEBUG = false) and check the log for any errors.
But if you insist to enable app debug dynamically, you can use middleware:
Create a new middleware using Artisan command:
php artisan make:middleware EnableDebug
This command will place a new EnableDebug class within your app/Http/Middleware directory. Modify it like this:
<?php
namespace App\Http\Middleware;
use Closure;
class EnableDebug
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
config(['app.debug' => $request->ip() === 'myipaddress']);
return $next($request);
}
}
List your middleware class at the end of the $middleware property of your app/Http/Kernel.php class:
protected $middleware = [
//...
\App\Http\Middleware\EnableDebug::class,
];
I am using the default laravel 5.2 authorization library.
I am using the remember me functionality with a 24 hour time out.
I need to log user_id with IP address in an audit table after each user visit to the webste.
I have done this using the EventServiceProvider, listening for the login event
and then using the request object to identify the IP and persisting to the database.
protected $listen = [
'Illuminate\Auth\Events\Login' => [
'App\Listeners\LogSuccessfulLogin',
],
This works for all logins where the login screen is used with username and password supplied by the user.
However if the user accesses the website via the session cookie (ie- login within 24 hours of the previous login) the login is not recorded. So it must follow a different path within the authorization library.
In the API documentation (https://laravel.com/api/5.2/Illuminate/Auth/Events.html) there is no event like for example 'LogInViaCookie'.
I have tried adding a method to AuthController-
/**
* Add audit.
*
* #param $request
* #param $user
*/
protected function authenticated(Request $request, $user)
{
try
{
$audit = Audit::create(['internet_protocol' => $request->ip,
'uid' => $user->id,
'general' => 'viaCookie']);
$audit->save();
}catch(\Exception $e){
Log::error($e->getMessage());
}
}
This authenticated method, as I understand it, should be fired from the AuthenticatesUsers trait (line 115)-
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
However, it appears this method is not fired when logging in via cookie.
How can I listen for and capture this type of 'LogInViaCookie' event to update my audit table?
UPDATE 30/05/16 21:21
Rifki- That sounds like a good solution. I've tried implementing but I can't get it to work.
This is my viaCookie.php-
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class viaCookie
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::viaRemember()) {
dd('logged in via cookie');
}
return $next($request);
}
}
And my Kernel.php update-
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\viaCookie::class,
],
Am I missing something? dd isn't being fired.
In my project, I am using Laravel purely as a backend api and all frontend is handled by Angular javascript. At the moment, the Laravel routes can be accessed directly and it will cough out all the data in Json that shows in the browser. I want to put a restriction on it so Laravel only responds to Ajax requests and nothing else.
I read this post here which has a solution for Laravel 4 that is by adding a restriction in filter.php. But as of Laravel 5.1, filters are no longer used and I believe Middleware can be used to do the same. However, I am not sure how to go ahead changing the Laravel 4 solution in that SO answer from filter to Middleware.
Can someone share your ideas on how to prevent Laravel 5.1 routes from being accessed directly please?
Laravel 4 solution using filter.php:
In filter.php declare this filter:
Route::filter('isAJAX', function()
{
if (!Request::AJAX()) return Redirect::to('/')->with(array('route' => Request::path()));
});
Then put all your routes that you only want accessible via AJAX into a group. In your routes.php:
Route::group(array('before' => 'isAJAX'), function()
{
Route::get('contacts/{name}', ContactController#index); // Or however you declared your route
... // More routes
});
Create the middleware file app/Http/Middleware/OnlyAjax.php with this content:
<?php
namespace App\Http\Middleware;
class OnlyAjax
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, \Closure $next)
{
if ( ! $request->ajax())
return response('Forbidden.', 403);
return $next($request);
}
}
Then register your middleware in the file app/Http/Kernel.php
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
//... your original code
];
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
//... your original code
'ajax' => \App\Http\Middleware\OnlyAjax::class,
];
}
And finally attach the middleware to any route or group of routes you want to make only accessible via AJAX. i.e:
/// File: routes/web.php
// Single route
Route::any('foo', 'FooController#doSomething')->middleware('ajax');
// Route group
Route::middleware(['ajax'])->group(function () {
// ...
});
I'm just taking the first look at laravel5
so with a new install I'm starting playing around
(as usual :) )
php artisan make:middleware OldMiddleware
<?php namespace App\Http\Middleware;
use Closure;
class OldMiddleware {
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($request->input('age') < 200)
{
return redirect('home');
}
return $next($request);
}
}
<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
'App\Http\Middleware\OldMiddleware',
];
/**
* The application's route middleware.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
}
when I hit
http://localhost/l5/public/
there is a redirect to
http://localhost/l5/public/home
with the message
The page isn't redirecting properly
What's the problem ?
I've just tried https://stackoverflow.com/a/30116118 but still not working :(
Put it in the $routeMiddleware..
protected $routeMiddleware = [
'home' => 'App\Http\Middleware\OldMiddleware',
];
and in your route..
Route::get('/', ['middleware' => 'home'], function() {
return "blah";
}
Route::get('/home', function() {
return "home";
}
Then if you go to example.com/ it go to the middleware and redirect's you to /home.
The The page isn't redirecting properly comes because a loop occurs.
PS: If you don't want the built in login etc. you can do
artisan fresh
..sometimes it's better to start fresh if you just want to playing around! ;)