laravel view can のカスタマイズは、userの「authorizeRoles」メソッドかも?→間違い

https://readouble.com/laravel/5.5/ja/authentication.html

Laravel 5.5 認証


ガードの指定
authミドルウェアをルートに対し指定するときに、
そのユーザーに対し認証を実行するガードを指定することもできます。
指定されたガードは、auth.php設定ファイルのguards配列のキーを指定します。

Laravel 5.3 認可
https://readouble.com/laravel/5.3/ja/authorization.html

指定するモデルのポリシーが登録済みであれば適切なポリシーの
canメソッドが自動的に呼びだされ、
論理型の結果が返されます。
そのモデルに対するポリシーが登録されていない場合、
canメソッドは指定したアクション名に合致する、
ゲートベースのクロージャーを呼びだそうとします。

【Laravel5.3】独自ポリシーでモデル以外の型の引数を指定できるか
https://teratail.com/questions/60628
@canを使わずにViewの制御をする方法あり

[Laravel]ミドルウェアを整理してLaravelを軽くする
https://qiita.com/kurikazu/items/0c57f050f5dfef02b23e
↑既存middlewareの整理ができる

https://readouble.com/laravel/5.3/ja/authorization.html
Laravel 5.3 認可

@canを
ViewにIFで書くとこんな感じ
@if (Auth::user()->can('update', $post))
    
@endif

@unless (Auth::user()->can('update', $post))
    
@endunless

Laravel5のログイン時に認証条件追加
https://saba.omnioo.com/note/3149/laravel5%E3%81%AE%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3%E6%99%82%E3%81%AB%E8%AA%8D%E8%A8%BC%E6%9D%A1%E4%BB%B6%E8%BF%BD%E5%8A%A0/
・vendor以下は触りたくない

Laravel 5.5 の認証機能とそのカスタマイズ
https://qiita.com/netfish/items/40076fd74536b0efdb2f

ログイン記録を残したり
認証カラムを変更したり

Laravel 5.5 の認証機能とそのカスタマイズ
https://qiita.com/naga3/items/4f3defde59b31a1a797e
・認証機能のソースの場所の情報
・ログイン時のリダイレクトの変更
・ログイン画面のView(HTML)の変更など

https://stackoverflow.com/questions/31790234/laravel-5-adding-hasrole-method-to-auth

↓これは、UserのauthorizeRolesメソッドViewを切り替える方法だけ
Medium.com で表示


Homepage
Go to the profile of everton zp
everton zp
Joinville — SC — Brazil
Mar 30, 2017
Laravel 5.4 (and 5.5) native User Authentication + Role Authorization
A very brief step-by-step of how to implement a native Laravel 5.4 user authentication + role authorization.

Disclaimer: This simple tutorial does not pretend to be the ultimate approach implementing ACL in your project. The main goal here is help you to grasp the very basics on this subject so after this first contact you can jump to a proper ACL library.

Starting from a fresh Laravel 5.4/5.5 installation, run the php artisan to create the Auth resource:

$ php artisan make:auth
Create the Role model and respective migration (-m parameter):

$ php artisan make:model Role -m
Edit CreateRolesTable class in the migrations folder:

public function up()
{
  Schema::create(‘roles’, function (Blueprint $table) {
    $table->increments(‘id’);
    $table->string(‘name’);
    $table->string(‘description’);
    $table->timestamps();
  });
}
public function down()
{
  Schema::dropIfExists(‘roles’);
}
Create a new migration for the role_user pivot table :

$ php artisan make:migration create_role_user_table
Edit CreateRoleUserTable class in the migrations folder:

public function up()
{
  Schema::create(‘role_user’, function (Blueprint $table) {
    $table->increments(‘id’);
    $table->integer(‘role_id’)->unsigned();
    $table->integer(‘user_id’)->unsigned();
  });
}
public function down()
{
  Schema::dropIfExists(‘role_user’);
}
Now let’s provide a many-to-many relationship between User and Role.

Open User model and add the following method:

public function roles()
{
  return $this->belongsToMany(Role::class);
}
Do the same with Role model:

public function users()
{
  return $this->belongsToMany(User::class);
}
It’s time to create some seeders to add roles and users in the database:

$ php artisan make:seeder RoleTableSeeder
$ php artisan make:seeder UserTableSeeder
Edit RoleTableSeeder class (database/seeds/ folder) adding the following code in run() method:

use Illuminate\Database\Seeder;
use App\Role;
class RoleTableSeeder extends Seeder
{
  public function run()
  {
    $role_employee = new Role();
    $role_employee->name = ‘employee’;
    $role_employee->description = ‘A Employee User’;
    $role_employee->save();
    $role_manager = new Role();
    $role_manager->name = ‘manager’;
    $role_manager->description = ‘A Manager User’;
    $role_manager->save();
  }
}
Do the same with UserTableSeeder class:

use Illuminate\Database\Seeder;
use App\User;
use App\Role;
class UserTableSeeder extends Seeder
{
  public function run()
  {
    $role_employee = Role::where(‘name’, ‘employee’)->first();
    $role_manager  = Role::where(‘name’, ‘manager’)->first();
    $employee = new User();
    $employee->name = ‘Employee Name’;
    $employee->email = ‘employee@example.com’;
    $employee->password = bcrypt(‘secret’);
    $employee->save();
    $employee->roles()->attach($role_employee);
    $manager = new User();
    $manager->name = ‘Manager Name’;
    $manager->email = ‘manager@example.com’;
    $manager->password = bcrypt(‘secret’);
    $manager->save();
    $manager->roles()->attach($role_manager);
  }
}
Edit DatabaseSeeder class (database/seeds/ folder) adding the following code in run() method:

public function run()
{
  // Role comes before User seeder here.
  $this->call(RoleTableSeeder::class);
  // User seeder will use the roles above created.
  $this->call(UserTableSeeder::class);
}
Almost done! Don’t give up! ^^

Open User model and add these three tiny methods:

/**
* @param string|array $roles
*/
public function authorizeRoles($roles)
{
  if (is_array($roles)) {
      return $this->hasAnyRole($roles) || 
             abort(401, 'This action is unauthorized.');
  }
  return $this->hasRole($roles) || 
         abort(401, 'This action is unauthorized.');
}
/**
* Check multiple roles
* @param array $roles
*/
public function hasAnyRole($roles)
{
  return null !== $this->roles()->whereIn(‘name’, $roles)->first();
}
/**
* Check one role
* @param string $role
*/
public function hasRole($role)
{
  return null !== $this->roles()->where(‘name’, $role)->first();
}
Open app/Http/Controllers/Auth/RegisterController.php and change the create() method to set a default Role for new Users:

use App\Role;
class RegisterController ...
protected function create(array $data)
  {
    $user = User::create([
      'name'     => $data['name'],
      'email'    => $data['email'],
      'password' => bcrypt($data['password']),
    ]);
    $user
       ->roles()
       ->attach(Role::where('name', 'employee')->first());
    return $user;
}
Run the migrate command with seed parameter. Next time you login, each user should have a role.

$ php artisan migrate:fresh --seed
Finally the final step! Now, all you need to do is call the User authorizeRoles() method inside your Controller Actions or Middlewares and pass an array with the user roles you want to grant access.

class HomeController extends Controller
{
  public function __construct()
  {
    $this->middleware('auth');
  }
  public function index(Request $request)
  {
    $request->user()->authorizeRoles(['employee', 'manager']);
    return view(‘home’);
  }
  /*
  public function someAdminStuff(Request $request)
  {
    $request->user()->authorizeRoles('manager');
    return view(‘some.view’);
  }
  */
}
After this point, just proceed with the normal development flow. Build a interface CRUD to manage roles and assign them to the users.

Credits: This article is inspired by this Academind video series.

LaravelPHPLaravel54
Like what you read? Give everton zp a round of applause.
From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.

Go to the profile of everton zp
everton zp
Joinville — SC — Brazil

Also tagged PHP
Building a User-Based Task List Application in Laravel
Go to the profile of Brice Hartmann
Brice Hartmann
Related reads
Testing Helpers in Laravel 5.4
Go to the profile of Connor Leech
Connor Leech
Also tagged PHP
Getting Started with Geospatial Data in Laravel
Go to the profile of Brice Hartmann
Brice Hartmann
Responses
Conversation with Vivek Kumar.
Go to the profile of Arief Budi Prasetyo
Arief Budi Prasetyo
Jul 7, 2017
how setting User authorizeRoles() if i want separate dashboard for employee and manager?

Go to the profile of Vivek Kumar
Vivek Kumar
Jul 14, 2017
In login controller you can do like this.

public function authenticated(Request $request)
 {
 // Logic that determines where to send the user
 if($request->user()->hasRole(‘user’)){
 return redirect(‘/user/home’);
 }
 if($request->user()->hasRole(‘admin’)){
 return redirect(‘/admin/home’);
 }
 }

Applause from everton zp (author)
Go to the profile of Abdalla Arbab
Abdalla Arbab
Jun 5, 2017
@ezp127 Very helpful and nice article. You should consider making a video tutorials in future. I hope you the best.

Applause from everton zp (author)
Go to the profile of Konstantin L.
Konstantin L.
Dec 13, 2017
You should better use exists() query instead of comparing null !== first()

Conversation between Rob and everton zp.
Go to the profile of Rob
Rob
Oct 31, 2017
Looks like there could be a small performance issue with the hasAnyRole() method… since it will run a query for each role it checks when it uses the hasRole() method.

If you are authorizing several roles with the authorizeRoles() method, that could mean several queries being run every time you authorize…

Go to the profile of everton zp
everton zp
Nov 1, 2017
Thanks for share this improvement! I’ll update the post with your suggestion.

Conversation between Er Ashok Sahu and everton zp.
Go to the profile of Er Ashok Sahu
Er Ashok Sahu
Aug 19, 2017
Great tutorial. How do you implement this in blade views? is it possible to check if a user hasRole with like an @if @endif etc or to show/hide menu bar

Go to the profile of everton zp
everton zp
Aug 30, 2017
Hello Er. You can try something like @if(Auth::user()->hasRole(‘manager’)) in your views.

Conversation between BouBou and everton zp.
Go to the profile of BouBou
BouBou
Oct 23, 2017
Hi, very good tutorial, will this work in laravel 5.5? Also can we protect the routes directly like:

//ADMIN ROUTES
Route::group([‘middleware’ => [‘role:admin’]], function () {

Route::get(‘myaccount’, function () { return view(‘admin/index’); });

Go to the profile of everton zp
everton zp
Oct 23, 2017
Yes, I think it will work the way you suggest. Take a look at this: https://laravel.com/docs/5.5/middleware#middleware-parameters

..and also works with Laravel 5.5

Conversation between Kali Dass and everton zp.
Go to the profile of Kali Dass
Kali Dass
Jun 20, 2017
I have implemented this, check out my repo : https://github.com/karoys/laravel-native-roles-auth

Go to the profile of everton zp
everton zp
Jun 27, 2017
Hello Kali Dass thank you very much for reference me on your repo. Best regards!

Conversation with Alan Colant.
Go to the profile of Arief Budi Prasetyo
Arief Budi Prasetyo
how setting User authorizeRoles() if i want separate dashboard for employee and manager?
Go to the profile of Alan Colant
Alan Colant
Aug 4, 2017
You can use:@if( Auth::user()->hasrole(‘manager’) )

to separate many element in blade template

Conversation between Keshia Darling and everton zp.
Go to the profile of Keshia Darling
Keshia Darling
Jul 29, 2017
Great tutorial. How do you implement this in blade views? is it possible to check if a user hasRole with like an @if @endif etc

Go to the profile of everton zp
everton zp
Aug 30, 2017
Hey Keshia, sorry by the delay haha. I think you can try something like @if(Auth::user()->hasRole(‘manager’)) in your views

Applause from everton zp (author)
Go to the profile of Tonye Roberts
Tonye Roberts
Aug 23, 2017
Nice article. I have been looking for a simple article on User Authentication / Role Authorization and this was just what I needed.

Applause from everton zp (author)
Go to the profile of Infete Watson
Infete Watson
Apr 15, 2017
Hi

Thanks so much for this great article, I learned how to make RBAC with it.

Applause from everton zp (author)
Go to the profile of Vivek Kumar
Vivek Kumar
Jul 13, 2017
Hi, I created complete role based authentication based on this tutorial but I am not able to redirect admin and user to different route after login. After login it is always getting redirected to home route. How can I redirect to different route. Thanks

Applause from everton zp (author)
Go to the profile of Moje Ime
Moje Ime
Jun 15, 2017
Thank you for a great tutorial. One thing I would add at Edit the RoleTableSeeder class section.
I overlooked “use App\Role;” at the begining. I just looked at the code below. I know its in bold letters but I would add a sentence before. Smth like don’t forget to include.. :)
Anyway great tutorial.

Conversation between Wayne Smallman and everton zp.
Go to the profile of Wayne Smallman
Wayne Smallman
Jun 14, 2017
Hi, when I ran: “php artisan make:model Role -m”, I got an error: “-bash: $: command not found”. Please ignore this comment (I’d copied the $ symbol in by mistake).

However, when I ran: “php artisan migrate:refresh — seed” I got an error telling me that the tables already existed.

Go to the profile of everton zp
everton zp
Jun 27, 2017
Hello Wayne. Did you managed to fix that database issue?

Applause from everton zp (author)
Go to the profile of weristsam.de
weristsam.de
Jul 1, 2017
first of all great job! great tutorial! that was one of the best tutorial i ever read.. thank you! :)

Applause from everton zp (author)
Go to the profile of Kavinda Karunarthna
Kavinda Karunarthna
Aug 22, 2017
Hi, this is very useful article and thank you very much for sharing the knowledge.

Applause from everton zp (author)
Go to the profile of Akuma Isaac Akuma
Akuma Isaac Akuma
Oct 11, 2017
Very nice you really helped me alot

thanks bro

Go to the profile of everton zp
Never miss a story from everton zp, when you sign up f
スポンサーリンク

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

スポンサーリンク