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
Related
I create a multiple Authentication in Laravel. When I login with user, on debug in post login method, after Auth::guard('user')->attempLogin..... I see a user but after redirect to HomeController this return null.
How to resolve? I'm beginner in Laravel.
Thank's!!!
/routes/auth/user.php
Route::prefix('backoffice')->name('user.')->namespace('User')->middleware('user')->group(function () {
Auth::routes();
Route::get('home', 'HomeController#index')->name('home');
});
/routes/web.php
Route::group(['middleware' => 'web'], function() {
require 'auth/user.php';
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('cadastro', 'CadastroController');
});
/app/Controllers/User/Auth/LoginController - #post Login
public function login(Request $request) {
$credentials = [
'username' => $_POST['username'],
'password' => $_POST['password']
];
Auth::guard('user')->attempt($credentials, false);
//dd('auth', Auth::guard('user'));
return redirect()->intended('/backoffice/home');
}
/app/Controllers/User/HomeController
public function __construct()
{
$this->middleware('user');
dd('after middleware', Auth::guard('user'), Auth::guard('user')->user());
}
public function index()
{
return view('user.home');
}
By default, Laravel doesn't ship with auth guard user. Perhaps you meant to use web guard i.e Auth::guard('web'). Auth::guard()->user() should return the logged in user object if a user is logged in.
Also, the default middleware for checking logged in user is auth, not user. So, your route might look like this: Route::prefix('backoffice')->name('user.')->namespace('User')->middleware('auth')->group(function () {});, except you've defined a custom middleware in app/Http/Kernel.php $routeMiddleware array with alias user
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 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);
}
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');
});
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';
}]);