Skip to content

Instantly share code, notes, and snippets.

@germanow
Created February 23, 2018 17:53
Show Gist options
  • Save germanow/219b9398f69148da5b161ec4d63b9790 to your computer and use it in GitHub Desktop.
Save germanow/219b9398f69148da5b161ec4d63b9790 to your computer and use it in GitHub Desktop.
Laravel role implementation
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoleTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->integer('role_id')->unsigned()->nullable();
$table->foreign('role_id')
->references('id')->on('role')
->onDelete('set null');
});
DB::table('role')->insert([
['name' => 'admin'],
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roles');
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
if (!Auth::check() || $request->user()->role !== 'admin') {
return redirect('/admin/login');
}
return $next($request);
}
}
<?php
namespace App\Http\Models\User;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = 'role';
protected $guarded = [];
public function users()
{
return $this->hasMany('App\Http\Models\User\User','role_id','id');
}
}
<?php
namespace App\Http\Models\User;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
public function roleModel()
{
return $this->belongsTo('App\Http\Models\User\Role','role_id');
}
public function getRoleAttribute()
{
return $this->roleModel->name;
}
}
<?php
Route::group(['prefix' => 'admin', 'middleware' => 'check_role:admin',], function () {
Route::get('/miss', 'MissController@welcome');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment