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

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');
});

Related

trying to assign one route to more than one middleware

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. :)

Returning a controller in Laravel 5.6 route file

I am trying to route a request to a controller method. When I do this it works:
Route::get('/path', 'controller#method');
I would like to set the locale before calling the controller. I tried different options and nothing works:
Route::get('/path', function(){
desired_function();
return action('controller#method');
});
and
Route::get('/path', function(){
desired_function();
return [
'uses' => 'controller#method'
];
});
What am I missing?
1) Create a app/Http/Middleware/SetLocale.php with content:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SetLocale
{
public function handle(Request $request, Closure $next)
{
\App::setLocale('en'); // or get it from request
// or:
// $request->attributes->set('locale', 'en');
// in action: $request->get('locale');
return $next($request);
}
}
2) Attach it to route:
Route::get('/path', 'controller#method')
->middleware('App\Http\Middleware\SetLocale');
or to route group:
Route::group([
'middleware' => [
'App\Http\Middleware\SetLocale'
]
],
function() {
Route::get('/path', 'controller#method');
});
if You want it to be used globally everywhere:
in app/Http/Kernel.php :
/**
* The application's global HTTP middleware stack.
*
* #var array
*/
protected $middleware = [
...
'App\Http\Middleware\SetLocale' // add it to end of array
];

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
}]);

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.

Laravel 5 Middleware

Hi I am using Middleware of Laravel 5 and what I am doing is I have middleware which is being used in few controllers, and each of my controllers has it's own configs, which I need to pass my middleware, how can I do that?
If you are using this Middleware in "Stack" (Defined at App/Http/Kernel.php in $middleware array), you don't have the $request->route() available.
BUT, if you are using it on routes.php file as middleware of a single route or group of routes, you can do this way:
Create a config file as you want, with config items named with same name of each route, then in your middleware you get route name and load proper configs.
Sorry if it's confuse, imagine this code:
Config/permissions.php
<?php
return [
// Route name here
'user.index' =>
// Your route options here
[
'option_a' => true,
'option_b' => false,
],
'user.edit' =>
[
'option_a' => true,
'option_b' => true,
],
/* ... */
];
?>
So in your middleware handle function you do something like this:
public function handle($request, Closure $next)
{
$route = $request->route()->getName();
/* Check if there is a permission to this route in config file */
if (\Config::get("permissions.{$route}")) {
$options = \Config::get("permissions.{$route}");
/* Here will be your options by route */
/* Now it's up to you do what you want */
} else {
/* If not, use default options */
}
return $next($request);
}
BTW, I recommend you using Laracast Discuss foruns:
www.laracast.com/discuss

Resources