laravel 5 middleware with parameters - php

I'm an absolute beginner in Laravel 5.
I've created a middleware class called BeforeMiddleware the blueprint of that class is below.
class BeforeMiddleware {
public function handle($request, Closure $next, $role)
{
if($request->user()->hasRole($role)){
return redirect('/pensions');
}
return $next($request);
}
}
registered in kernel.php as
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'role' => 'App\Http\Middleware\BeforeMiddleware',
];
User model is below
class User extends Model {
public function hasRole($name)
{
return ($this->role->name == $name) ? true : false;
}
public function role()
{
return $this->belongsTo('App\Models\Role');
}
}
and usage in routes.php is below.
Route:get('/reporting', [ 'middleware' => 'role:Owner', 'uses' => function(){
return 'secret data only be viewable by the owners';
}]);
If I open that in the browser /reporting I get the following error.
ReflectionException in Container.php line 776:
Class role:Owner does not exist
HOWEVER if I hard code 'Owner' in middleware and remove the $role parameter and also removed it from routes which now looks like this.
BeforeMiddleware.php
class BeforeMiddleware {
public function handle($request, Closure $next, $role)
{
if($request->user()->hasRole('Owner')){
return redirect('/pensions');
}
return $next($request);
}
}
routes.php
Route:get('/reporting', [ 'middleware' => 'role', 'uses' => function(){
return 'secret data only be viewable by the owners';
}]);
it works as desired...
therefore my question is how to pass that parameter when using middleware to control routes
Any Idea?

If you read carefully the Middleware Documentation, you will notice this line
Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas
So in your case if your middleware class is called BeforeMiddleware, the first part of middleware definition should be before then :, and after that you can define your route parameters, separated with comma, like this:
Route:get('/reporting', [ 'middleware' => 'before:Owner', 'uses' => function(){
return 'secret data only be viewable by the owners';
}]);

Since you are using Laravel 5.0, I suggest to just create separate middlewares for your roles.
Kernel.php
'owner' => 'App\Http\Middleware\OwnerMiddleware',
OwnerMiddleware
public function handle($request, Closure $next)
{
if($request->user()->hasRole('Owner')){
return redirect('/pensions');
}
return $next($request);
}
Then in routes.php
Route:get('/reporting', [ 'middleware' => 'owner', 'uses' => function(){
return 'secret data only be viewable by the owners';
}]);

Related

Route [events] not defined using laravel

I want when I type the address http://localhost/agendab/public or when I open my web application, it will redirect directly to login, or when I click on disconnect, it will redirect to login.
web.php
Auth::routes();
Route::resource('events', 'EventController')->middleware('auth');
loginController.php
protected $redirectTo = '/events';
public function login(Request $request)
{
$input = $request->all();
$this->validate($request, [
'name' => 'required',
'password' => 'required',
]);
$fieldType = filter_var($request->name, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
if(auth()->attempt(array($fieldType => $input['name'], 'password' => $input['password'])))
{
return redirect()->route('events');
}else{
return redirect()->route('login')
->with('error','Email-Address And Password Are Wrong.');
}
}
Http/Middleware/RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/events');
}
return $next($request);
}
When you use Laravel resources, you need pre-defined way to call. Ex for the index you have to call events.index, if update then events.update...
In case you're calling a custom route in the same EventsController the defied it before the resource route.
In RedirectIfAuthenticated.php
if (Auth::guard($guard)->check()) {
return redirect('/events.index');
}
or
return Redirect::route('events.index'); #using facade
return redirect()->route('events.index'); #using helper class
FYK
HTTP Redirects
Actions Handled By Resource Controller
Resource Controllers
Redirect proper route name
return redirect()->route('events.index'); // loginController.php

How to prevent a parameter from getting injected in controller methods in Laravel

I am creating a multilingual website in Laravel. I need urls to be like that:
https://website.com/en/admin/user/1
https://website.com/ar/admin/user/1
so my route file looks like that:
Route::group(['prefix' => '{locale}'], function(){
Route::middleware("locale")->group(function () {
Route::group(['prefix' => 'admin', 'as' => "admin.", "namespace" => "Admin"],function(){
Route::get('login', 'LoginController#index')->name("signin")->middleware("Guest");
Route::post('login', 'LoginController#login')->name('login')->middleware("Guest");
Route::group(["middleware" => "Admin"], function (){
Route::get('/', ["as" => "dashboard", "uses" =>'DashboardController#index']);
Route::get('logout', 'LoginController#logout')->name('logout');
Route::resource('users', 'UsersController');
});
});
});
});
My middleware "locale":
public function handle($request, Closure $next)
{
URL::defaults(['locale' => $request->segment(1)]);
if(in_array($request->segment(1), config('app.locales')))
{
app()->setLocale($request->segment(1));
}
return $next($request);
}
Now the problem is that when I try to call a use a route with parameters I have to add the locale as a first parameter. For example:
this is a method in UsersController:
public function destroy($locale, $id)
{
//Any Code
}
I have to add $locale as a parameter to the method to be able to use the other parameters or the $id will have the value of the $locale which is "en", "ar" instead of the user id. So is there any way I can avoid that so my method will look like:
public function destroy($id)
{
//Any Code
}
You can build your routes for example like this:
Route::group(['prefix' => app()->getLocale()], function(){
so you will get rid of locale route parameter.

How to get all user details from laravel5.3

How i get all users in laravel 5.3 . i am using barryvdh for cors
this is my RegisterController which is in Auth folder
public function index(){
return Users::all();
}
above code gives all the user data if in route below we do not use middleware
and if we use middleware then i got error unauthenticated . so i want to get all user data using middleware in route . How can i get
Route::get('/users','Auth\RegisterController#index')->middleware('auth');
I think you can try this :
public function index(){
$users = Users::get();
return $users;
}
Hope this work for you!
So if you want to get all data of your user table you simple have to do following:
# Middleware group if user is logged in
Route::group(['middleware' => 'auth'], function ()
{
Route::get('home', ['as' => 'home', 'uses' => 'HomeController#index']);
Route::group(['prefix' => 'user'], function ()
{
Route::get('get', ['as' => 'getUser', 'uses' => 'UserController#getUser']);
});
});
And in your controller you can do something like this:
class UserController extends Controller
{
public function getUser(Request $request)
{
$users = DB::table('users')->get();
return $users;
}
}
If you want add something to that return you probably have to create a relation between your models, and call them in your method and return them.
If you still have any questions or if I understood something wrong feel free to comment on this answer.
Edit:
If you want to return all user with an api route you can do following in your api routes:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Try this
public function index()
{
$userDetail = Users::get();
dd($userDetails);
}

How to use role based access in laravel using entrust

I am using Laravel 5.4. I want to assign all authority to 'Admin' role. But Employee cannot delete or edit records. I'm using Entrust Package for Role based permission.
I've written routes for this but unfortunately Its not working for employee.
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () {
// Route::resource('plotsize', 'plotSizeController');
Route::group(['middleware' => 'role:Employee'], function () {
Route::resource('plotsize', 'plotSizeController', ['except' => 'edit', 'update', 'delete']);
});
Route::group(['middleware' => 'role:Admin'], function () {
Route::resource('plotsize', 'plotSizeController');
}); });
This is another approach that I had tried but unfortunately Its also not working.
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
if(Auth::user()->hasRole('Admin')){
$this->middleware('role:Admin');
return $next($request);
}
if(Auth::user()->hasRole('Employee')){
$this->middleware('role:Employee', ['only' => ['edit', 'update', 'destroy']]);
return $next($request);
}
});
}
If you're giving me suggestion to use Policy in Laravel. I've tried that but I'm not getting what's the issue on this. Can you provide me any example for this? Thanks

Laravel Auth redirect not working

I am using Laravel v5.2.39. I want to redirect to dashboard only, if you are logged in. If you change URL manually, it will redirect you to home screen. I am using auth middleware, but it doesn't work. Any help?
My routes.php file:
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::get('dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
My UserController.php:
public function getDashboard(){
return view('dashboard');
}
And auth middleware:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('home');
}
}
return $next($request);
}
I don't know, whats the problem with. I have some sign in and sign up too, but i dont think this is problem. If somenone wanna see it, write me.
Have a nice day and thank you.
As mentioned above, have you tried something like this?
Route::group(['middleware' => 'auth'], function () {
Route::get('dashboard', 'UserController#getDashboard')->name('dashboard');
});
Or you can add the middleware in the construct function in your class like so :
public function __construct() {
$this->middleware('auth');
}
Also, see the laravel documentation on using middleware with routes.
Try using 'middleware' => 'auth:web' in place of 'middleware' => 'auth'
Hey im not clear about your problem but this will help you,
when you go for project path localhost/project/ it will redirect to localhost/project/home URL in that URL u can assign any function
Route::get('/', function () {
return redirect('home');
});

Categories