Add middleware to controller in __construct in Laravel - php

I am trying to assign a middleware in __construct of a controller based on Laravel docs but it throws the follwing error:
BadMethodCallException
Method App\Http\Controllers\MyController::middlware does not exist.
that is my controller class:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class MyController extends Controller
{
public function __construct()
{
$this->middleware('myauth');
}
/** something */
public function index()
{
return view('test.hi', ['name' => 'Moh']);
}
}
And here is the middleware code:
<?php
namespace App\Http\Middleware;
use Closure;
class myauth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
echo time().'<br>';
return $next($request);
}
}
Laravel version: 6.5.2
Where am I doing wrong?

Middleware can be specified within controller's constructor
public function __construct() {
$this->middleware('auth');
}
For whole controller:
$this->middleware('auth');
Only for a particular action:
$this->middleware('auth')->only('index');
For whole controller except particular action:
$this->middleware('auth')->except('store');

The function is middleware, you have a typo, missing an e.

Firstly ask to you, Your error is middlware name is incoorect you missed e after that check the below middleware process.
Laravel Middleware - Middleware acts as a middleman between a request and a response.
Firstly goto project folder and open cmd and use this command
php artisan make:middleware MiddlewareName
after that go to App\Http\kernel.php and add one lines on $routeMiddleware
'user_block' => \App\Http\Middleware\MiddlewareName::class
After that goto your middleware
In handle function (write your own middleware code)
In routes use your middleware -
Route::group(['middleware' => ['user_block']],
function () {
Route::get('/logout', array('uses' => 'Auth\LoginController#logout'));
});
If you used this middleware in specific controller in __construct in any controller just write a line
namespace App\Http\Controllers;
use App\User;
class UserController extends Controller {
public function __construct() {
$this->middleware('user_block');
}
}
If you want this middleware for just one action in the controller you can add this middleware to the route :
Route::get('/login', 'LoginController#login')->middleware('user_block');
If you used this middleware in specific controller in specific 1-2 function just write this line in __construct functiono in controller
public function __construct()
{
$this->middleware('user_block')->only(['login','register']);
}

Related

Can't get session variables in AppServiceProvider

I would like to share some variables from session in all views in Laravel 8. According to documentation I call View::share() method in AppServiceProvider:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
// Variables shared in all views.
View::share('showModal', session('showModal'));
}
}
The problem is that although the session showModal key is really set, I can't get it in AppServiceProvider::boot(). If I call session('showModal') in the controller on in view I can see the correct value. Only AppServieProvider returns null.
Can somebody explain please what is wrong with this code?
Well, alternatively, you could set up a middleware to be responsible for updating your session variable before the call in view.
Below is something I implemented for setting/retrieving the user permissions before the call in view.
STEP 1
Generate the middleware: php artisan make:middleware GetPermissions
You will find the middleware in App\Http\Middleware directory.
STEP 2
Add your logic for setting your session variable in the new middleware's handle method.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class GetPermissions
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
$request->session()->put("permissions", optional(auth()->user(), function ($user) {
return $user->permissions()->pluck("name")->toArray();
}) ?? []);
return $next($request);
}
}
STEP 3
Register your middleware in the protected $middlewareGroups array of App\Http\Kernel.php class file.
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
// ...
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\GetPermissions::class,
],
// ...
}
With that setup, every time a request is made, the latest values of your session variable will be set.
You will then have access to latest session variable value in your helperfiles, controllers as whereas views.
Demo for accessing it in views:
{{session("permissions")}}

Use custom middleware in controller

I created middleware: php artisan make:middleware CheckUserStatus
In this middleware I have:
namespace App\Http\Middleware;
use Closure;
class CheckUserStatus
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth()->check() AND Auth()->user()->status === 0) { // user is logged in but it is blocked
auth()->logout();
return redirect('/');
}
return $next($request);
}
}
Then, one of my controller I have:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Middleware\CheckUserStatus;
class productsController extends Controller
{
public function __construct () {
$this->middleware('auth');
$this->middleware('CheckUserStatus');
}
}
This gives ReflectionException - Class CheckUserStatus does not exist
What I'm doing wrong ?
You need to register your middleware if you want to reference it by a string key. Check out the docs here.
Alternatively, you could use the fully qualified class name: try CheckUserStatus::class instead of 'CheckUserStatus'.
You need to use the fully qualified class name:
Either:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class productsController extends Controller
{
public function __construct () {
$this->middleware('auth');
$this->middleware('\App\Http\Middleware\CheckUserStatus');
}
}
or
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Middleware\CheckUserStatus;
class productsController extends Controller
{
public function __construct () {
$this->middleware('auth');
$this->middleware(CheckUserStatus::class); //No quotes
}
}
You need to add your middleware in kernel.php
protected $routeMiddleware = [
'your_desire_name'=>\App\Http\Middleware\CheckUserStatus::class,
];

Auth middleware not redirecting to login page

I have this situation where I have a route /admin which requires Auth middleware to be activated. I have the middleware requirement indicated in the web.php route. Also, I do have the default auth setup of laravel.
The kernel.php does have the middleware indicated too.
But, weirdly enough /admin brings me to a white page with nothing. When logged in, the problem isn't there. It had been working and all of a sudden it was not working anymore.
The auth middleware is as it is:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string
*/
protected function redirectTo($request)
{
return route('login');
}
}
The controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\NewsletterSubscribers;
use App\User;
use File;
class adminController extends Controller
{
//
public function __construct()
{
$this->middleware('auth');
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
public function changebg(){
return view('admin.changebg');
}
public function changebgimage(Request $request){
$this->validate($request,
[
'image'=>'required|image|mimes:jpg,JPG,jpeg,JPEG|max:4096|dimensions:max_width:1600,max_height:1100',
]
);
$path="images/";
$imagepath="images/bg.jpg";
if( File::exists($imagepath))
{
unlink($imagepath);
}
if ( ! File::exists($path) )
{
File::makeDirectory($path,0777,true);
}
$getimageName = "bg.jpg";
$request->image->move(public_path($path), $getimageName);
return view('admin.home');
}
public function newslettersubscriberslist(){
$newslettersubscribers= NewsletterSubscribers::all();
$count=0;
return view('admin.subscriberslist',compact('newslettersubscribers','count'));
}
public function registerAdmin(){
return view('auth.adminregister');
}
public function viewAdmins(){
$admins= User::select('users.*')->where('role','=','admin')->get();
//print_r($admins);
$count=0;
return view('admin.adminlist',compact('admins','count'));
}
public function viewUsers(){
$users= User::select('users.*')->where('role','=','user')->get();
//print_r($admins);
$count=0;
return view('admin.userlist',compact('users','count'));
}
}
The admin middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class Admin
{
/**
* 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()->role == 'admin') {
return $next($request);
}
else {
return redirect('/login');
}
}
}
The the route I'm using:
Route::get('/admin', 'AdminController#index')->name('adminhome')->middleware('auth');
I dont find anything weird here but weirdly enough the problem exists. Can you guys trace somethin unusual here or somewhere it can be??
First of all, make sure you have error reporting turned on. Also take a look at laravel log. Looking at your code the problem might be case of AdminController. In routes you have 'AdminController#index' but the class you showed has name adminController and it should be AdminController. I also don't know what is the name of file but it should be again AdminController.php
You can use the middleware like this
Route::group(['middleware'=>'auth'], function()
{
Route::get('/admin', 'AdminController#index')->name('adminhome');
}

notfoundhttp exception while post request

I have researched all the previous answers of this similar question, yet I couldnt found any.
I am simply accessing the function which I have made custom
Routes
Route::post('dashboard', 'Admin\UserController#index');
UserController.php
<?php
namespace App\Http\Controllers;
use DB;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
echo "welcome"
}
}
When I am trying this,it throws me
NotFoundHttpException in RouteCollection.php line 161:
error.
Update
My all routes are
Route::get('/', function () {
return view('welcome');
});
// Authentication routes...
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Registration routes...
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
// Dashboard routes
Route::post('dashboard', 'Admin\UserController#index');
Route::controllers([
'password' => 'Auth\PasswordController',
]);
As You mentioned the issue its Not Getting the Path of Controller in namespace:
Try To Change namespace with this
namespace App\Http\Controllers\Admin;
and your Routes will be like this: Route::post('dashboard', 'UserController#index');
In the UserController you have used
namespace App\Http\Controllers;
which is not correct with the route you are using. It should be namespace
App\Http\Controllers\Admin;
Secondly, it will be proper if you have the route of dashboard as get:
Route::get('dashboard', 'Admin\UserController#index');
Routes
Route::post('dashboard', 'Admin\UserController#index');
UserController.php
<?php
namespace App\Http\Controllers\Admin;
use DB;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
echo "welcome"
}
}
namespace you need to add Admin in your controller
namespace App\Http\Controllers\Admin;
Since in your route you have Admin
Route::post('dashboard', 'Admin\UserController#index');
Updated
As per your comment you are accessing via
http://localhost/travelling/dashboard but if you are using localhost then you have to add public
http://localhost/travelling/public/dashboard
Also make sure since its POST reuqest you cant access Url directly from the browser.you need to use curl or html form with csrf token
Update
Since you have added $this->middleware('auth'); in constructor so you have to login

php Laravel ~ Attribute [controller] does not exist

I am trying to set up an Route Controller in my Laravel project and I have set up the controller and also the route.
However, when I load the route in the web.php then it produces an error when I try to navigate to that page in the browser of Attribute [controller] does not exist
Here is the code..
<?php
namespace CMS\Http\Controllers\Auth;
use CMS\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers {
logout as performLogout;
}
/**
* Where to redirect users after login.
*
*/
protected $redirectTo;
/**
* Create a new controller instance.
*
*/
public function __construct()
{
$this->redirectTo = route('backend.dashboard');
$this->middleware('guest')->except('logout');
}
public function logout(Request $request)
{
$this->performLogout($request);
return redirect()->route('auth.login');
}
}
And then in the web.php I have this...
Route::controller('auth', 'Auth\LoginController', [
'getLogin' => 'auth.login'
]);
The controller method is deprecated since Laravel 5.3. But now, you can use the resource method, which is meant for the same purpose as the controller method.
Like This:
Route::resource('auth', 'LoginController');
or
Route::get('/auth','LoginController');
Route::post('/auth','LoginController');

Categories