Hello i am learning laravel for first time on topic controllers.I need to get this output
First Middleware,
Second Middleware,
URI: usercontroller/path,
URL: http://localhost:8000/usercontroller/path,
Method: GET
My Following codes are:
UserControler.php
namespace FirstProject\Http\Controllers;
use Illuminate\Http\Request;
use FirstProject\Http\Requests;
use FirstProject\Http\Controllers\Controller;
class UserController extends Controller
{
public function _construct(){
$this->middleware('auth');
}
}
FirstMiddleware.php
namespace FirstProject\Http\Middleware;
use Closure;
class FirstMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
echo "<br>First Middleware";
return $next($request);
}
}
SecondMiddleware.php
namespace FirstProject\Http\Middleware;
use Closure;
class SecondMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
echo "<br>Second Middleware";
return $next($request);
}
}
SecondUserController.php
namespace FirstProject\Http\Controllers;
use Illuminate\Http\Request;
use FirstProject\Http\Requests;
use FirstProject\Http\Controllers\Controller;
class SecondUserController extends Controller
{
public function __construct(){
$this->middleware('Second');
}
public function showPath(Request $request){
$uri = $request->path();
echo '<br>URI: '.$uri;
$url = $request->url();
echo '<br>';
echo 'URL: '.$url;
$method = $request->method();
echo '<br>';
echo 'Method: '.$method;
}
}
Routes/web.php
Route::get('/usercontroller/path',[
'middleware' => 'First',
'uses' => 'UserController#showPath'
]);
But When im running http://localhost:8000/usercontroller/path
I m getting
BadMethodCallException
Method [showPath] does not exist on [FirstProject\Http\Controllers\UserController].
What is the problem?
It is quite obvious, isn't it ? This method is defined in SecondUserController but not in UserController and in routes you use 'UserController#showPath'
Related
Alright, so I created a middleware for my staff access only page but every time I get this error when I hop on the test site: Call to undefined function App\Http\Middleware\web()
Here's my code:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
class webAPIchecker
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$route = $request->route()->getName();
$middleware = $request->route()->middleware();
$post = $request->isMethod('post');
// Offline
$adminsOnlyPass = config('web.offlinePass');
if ((web('offline_enabled') && !in_array(session('admins_only'), $adminsOnlyPass)) || !web('offline_enabled') && session()->has('admins_only'))
session()->forget('admins_only');
if (web('offline_enabled') && !session()->has('admins_only') && !Str::startsWith($route, 'offline.'))
return redirect()->route('offline.offline');
if (!web('offline_enabled') && Str::startsWith($route, 'offline.'))
return $this->disabled('Offline', $middleware, $post);
return $next($request);
}
}
Instead of:❌
web('offline_enabled')
Use this:✅
auth()->user()?->offline_enabled
I want to use middleware in laravel but show that.
enter image description here
I think my code is right.
Wazawaza2Middleware.php
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class Wazawaza2Middleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check()){
return $next($request);
}else{
return view('auth.login');
}
}
}
web.php
use App\Http\Middleware\Wazawaza2Middleware;
Route::get('topde', 'ReviewController#top')->middleware('Wazawaza2Middleware::class');
Kernel.php
protected $routeMiddleware = [
.
.
.
'wazawaza2' =>
\App\Http\Middleware\Wazawaza2Middleware::class,
];
You have an error in your web.php, should be:
use App\Http\Middleware\Wazawaza2Middleware;
Route::get('topde', 'ReviewController#top')->middleware(Wazawaza2Middleware::class);
OR (since you are aliasing it)
Route::get('topde', 'ReviewController#top')->middleware('wazawaza2');
So I'm trying to use middleware to authenticate users on a few pages of my application, but I'm getting this error:
Class 'App\Http\Middleware\CheckAuth' not found
Here's CheckAuth.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Middleware\CheckAuth as Middleware;
class CheckAuth extends Middleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->auth > 0) {
return redirect()->route('dashboard');
}
return $next($request);
}
}
and here's Kernel.php:
protected $routeMiddleware = [
...
'authenticated' => \App\Http\Middleware\CheckAuth::class
];
When I try to use the middleware (like this ->middleware('authenticated');) I get the error.
Thanks.
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class CheckAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->auth > 0) {
return redirect()->route('dashboard');
}
return $next($request);
}
}
Remove use App\Http\Middleware\CheckAuth as Middleware; you're in the same Class File. you don't need to use it again.
Remove this line from the top of middleware.
use App\Http\Middleware\CheckAuth as Middleware;
And you don't need to extends that Middleware as well
Now, your code looks like below.
namespace App\Http\Middleware;
use Closure;
use Auth;
class CheckAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->auth > 0) {
return redirect()->route('dashboard');
}
return $next($request);
}
}
Use command to create middleware
php artisan make:middleware CheckAuth
I have a route in my web.php that returns a view:
Route::get('/', function () {
return view('welcome');
});
welcome is default Laravel view welcome.blade.php.
I have Middleware called AlwaysReturnJson and it contains:
<?php
namespace App\Http\Middleware;
use Closure;
class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
I set up this middleware in Kernel.php as global middleware:
protected $middleware = [
\App\Http\Middleware\AlwaysReturnJson::class
];
What I expect is to get plain text/json of welcome file in my browser when I navigate to given route but I always get it as html and it render page properly. I checked it, it applies middleware on every request so that is not a problem. Why is this happening and shouldn't it convert that view to a plain text? Am I doing something wrong?
If you want to set a header for your response you can do this:
namespace App\Http\Middleware;
use Closure;
class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
If you want to force return valid json content use this middleware instead:
namespace App\Http\Middleware;
use Closure;
class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return response()->json($response->getContent());
}
}
See Laravel docs about after middleware for more info.
You can alternatively return json response on your controller without any middleware needed:
Route::get('/', function () {
return response()->json(
view('welcome')->render()
);
});
You may want to use laravel After middleware (the middleware would perform its task after the request is handled by the application) and then set the content-type of response.
<?php
namespace App\Http\Middleware;
use Closure;
class AfterAlwaysReturnJson
{
public function handle($request, Closure $next)
{
$response = $next($request);
return $response->header('Content-Type', 'application/json');
}
}
Generally speaking this should be a rather simple problem. IT should be very similar to the following question on Stack Overflow
But seeing as it has been two years, maybe some of the syntax has changed.
All I want to do is pass a variable from the middleware to the controller, so I'm not duplicating mysql queries.
Here is my middleware:
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$id = $request->user()->id;
$rr = $request->user()->isSuperAdmin();
if ($request->user()->isSuperAdmin()) {
$request->merge(['group' => 123]);
return $next($request);
}
echo "not admin";
}
}
So the middleware works fine and if I DD($request) on the middleware I see my group => 123 on the page. (Right now it's 123 for the sake of simplicity.)
So I want to pass it to my AdminController:
<?php
namespace SleepingOwl\Admin\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use SleepingOwl\Admin\Form\FormElements;
use SleepingOwl\Admin\Form\Columns\Column;
use SleepingOwl\Admin\Display\DisplayTable;
use Illuminate\Contracts\Support\Renderable;
use SleepingOwl\Admin\Display\DisplayTabbed;
use Illuminate\Validation\ValidationException;
use SleepingOwl\Admin\Contracts\AdminInterface;
use SleepingOwl\Admin\Model\ModelConfiguration;
use Illuminate\Contracts\Foundation\Application;
use SleepingOwl\Admin\Contracts\Form\FormInterface;
use SleepingOwl\Admin\Contracts\ModelConfigurationInterface;
use SleepingOwl\Admin\Contracts\Display\ColumnEditableInterface;
class AdminController extends Controller
{
/**
* #var \DaveJamesMiller\Breadcrumbs\Manager
*/
protected $breadcrumbs;
/**
* #var AdminInterface
*/
protected $admin;
/**
* #var
*/
private $parentBreadcrumb = 'home';
/**
* #var Application
*/
public $app;
/**
* AdminController constructor.
*
* #param Request $request
* #param AdminInterface $admin
* #param Application $application
*/
public function __construct(Request $request, AdminInterface $admin, Application $application)
{
$this->middleware('CheckRole');
So as you can see I call the middleware on this constructor. After calling it I should be able do something like:
$request->get('group'); or $request->group;
After trying for quite a while nothing seems to be working and I keep getting a null value. Fundamentally, this shouldn't be terribly difficult, but I seem to have my syntax off or not using the right name spaces?
Instead of this code line:
$request->merge(['group' => 123]);
You can try:
$request->request->add(['group' => 123]);
What this code line will do is if a parameter named group exists in the $request it will overwrite with the new value, otherwise it will add a new parameter group to the $request
In your controller, you can get the value of group parameter as:
$group = $request->group; OR $group = $request->input('group');
Thanks to the joint help of #Rahul-Gupta and #shock_gone_wild. It was a joint effort I guess.
The first issue is that I'm using sleepingOwl laravel boilerplate. Probably not the best idea for someone new to Laravel. (not new to MVC / PHP).
Based on #shock_gone_wild comment, decide move my test over to a simple controller, and not the sleeping owl nonsense. (they have a lot of code.) Anyways, I believe that helped. I did leave the middleware in the constructor because I didn't apply the middleware to the routes.
Then I followed #Rahul-Gupta syntax.
So here is final result, hopefully this will save someone sometime someday...
namespace App\Http\Middleware;
use Closure;
class CheckRole {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next) {
if ($request->user()->isSuperAdmin()) {
$request->request->add(['group' => 123]);
return $next($request);
} else {
echo "not admin";
}
}
}
Then here is the simple controller.
use Illuminate\Http\Request;
use App\task;
use App\User;
use App\HasRoles;
class TaskController extends Controller {
public function __construct() {
// constructor code...
$this->middleware('auth');
$this->middleware('CheckRole');
}
public function index(Request $request) {
$group = $request->input('group');
echo "---->" . $group;
$tasks = Task::all();
return view('test_task', compact('tasks'));
}
}