I have two tables user and roles table with their respective Models with Many to Many Relationship. Giving them with a pivot table user_roles that contains 'user_id' and 'role_id' column
these are the files:
User.php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Carbon\Carbon;
class User extends Authenticatable {
protected $fillable = [ 'name', 'email', 'password'];
protected $hidden = [
'password',
'remember_token'
];
public function setPasswordAttribute($password) {
$this->attributes['password'] = bcrypt($password);
}
public function setBirthdateAttribute($birthdate) {
$this->attributes['birthdate'] = Carbon::createFromFormat('Y-m-d', $date);
}
public function roles() {
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
}
}
Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User','user_roles','role_id','user_id');
}
}
What my Problem is with my Middleware Redirection
Here is my Middleware File RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\Guard;
class RedirectIfAuthenticated {
protected $auth;
public function __construct(Guard $auth) {
$this->auth = $auth;
}
public function handle($request, Closure $next) {
if ($request->user() === null) {
return response()->view('errors.401');
} else {
if ($this->auth->check()) {
// -> don't have any algorithm here or any idea
switch ($auth) {
case '1':
return redirect('home');
break;
case '2':
return redirect('admin');
break;
default:
return redirect('user');
}
}
return $next($request);
}
}
}
My problem is that I need a piece of code in that commented line above that makes this one work. My approach is to Check the currently logged on user's ID, that match in the user_roles table 'role_id' column. Thanks