Laravel Nova not persisting new model - php

I am running into a weird problem of Laravel Nova not being able to persist any of my models. Trying to save a user on a fresh Nova install and using the default User resource created still fails. (Updating a user entry works though).
The error I am getting back when trying to create a new user is:
No query results for model [App\User].
Looking into Laravel Nova Core, the file responsible for this is: vendor/laravel/nova/src/Http/Controllers/ResourceStoreController.php
Inside this function, if I try to manually save a new model
dd((new User())->create(['name' => '', 'email' => '', etc]));
it successfully outputs the model but still doesn't have it saved in the database.
The same code when placed either in Tinker / any of the other web routes, successfully creates a new model and saves it in the DB.
My app\Nova\User.php:
<?php
namespace App\Nova;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Gravatar;
use Laravel\Nova\Fields\Password;
class User extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\\User';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'name';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'name', 'email',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Gravatar::make(),
Text::make('Name')
->sortable()
->rules('required', 'max:255'),
Text::make('Email')
->sortable()
->rules('required', 'email', 'max:254')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
Password::make('Password')
->onlyOnForms()
->creationRules('required', 'string', 'min:8')
->updateRules('nullable', 'string', 'min:8'),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
User Model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
My User table migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Any idea what might be tripping up a save operation this way? For additional info my setup is as follows:
Laravel (5.8)
Nova (2.5)
PHP 7.2
MySQL Ver 15.1 Distrib 10.4.6-MariaDB

Turned out the issue was with my MariaDB installation. Having recently upgraded it, I guess there may have been some configuration that caused mayhem. Moving away from MariaDB to MySQL 8 solved the issue.

Do not initialize a new Model class when using mass assignment, call the static method ::create()
\App\User::create(['name' => '', 'email' => '', etc]);
Also make sure that all properties are fillable in the User model
protected $fillable = [
'name', 'email', 'password', // Add the rest
];
or you can do what I do
protected $guarded = []; // yolo
Hope this helps

Related

How to establish relationship in Laravel, to store id and retrieve as object

I'm building a CRUD using Laravel and Angular technologies. However, as I am new to Laravel technology, I am not able to establish a relationship between two entities.
I have Group entity and Subgroup entity. A group has only its id and its name as attributes. A subgroup has its id, name and also a group id.
I would like to know how can I establish a relationship between group and subgroup. I want to store the id of a group in a subgroup record, but when performing queries with the HTTP verb I want the Group object to be returned and not its id, so that I can manipulate this object in the front-end.
Model Group:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
protected $table = 'groups';
}
Group Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Group Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('groups');
}
};
Subgroup Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubgroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'group_id' => $this->group_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Subgroup Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Subgroup extends Model
{
use HasFactory;
protected $fillable = [
'group_id'
];
protected $table = 'subgroups';
}
Subgroup Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('subgroups', function (Blueprint $table) {
$table->increments('id');
$table->foreignIdFor(Group::class);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('subgroups');
}
};
Subgroup Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Subgroup;
class SubgroupController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Subgroup::all();
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return Subgroup::create($request->all());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return Subgroup::find($id);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
if (Subgroup::where('id', $id)->exists()) {
$subgroup = Subgroup::find($id);
$subgroup->group_id = $request->group_id;
$subgroup->save();
return response()->json([
"message" => "Success"
], 200);
} else {
return response()->json([
"message" => "Error"
], 404);
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
if (Subgroup::where('id', $id)->exists()) {
$subgroup = Subgroup::find($id);
$subgroup->delete();
return response()->json([
"message" => "Successfully deleted"
], 202);
} else {
return response()->json([
"message" => "Not Found"
], 404);
}
}
}
I would like to know if I'm on the right path of establishing a relationship between the tables. Also, when retrieving a Subgroup I would like the group_id field not to return the id but a group object, how can I do that?
You have to use Relationships, it is a whole section on the documentation...
So, I think you want a 1-to-N (one to many), so one Group can have multiple Subgroups.
If that is the case, you should have:
Group model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
public function subgroups()
{
return $this->hasMany(Subgroup::class);
}
}
Subgroup
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Subgroup extends Model
{
use HasFactory;
protected $fillable = [
'group_id'
];
public function group()
{
return $this->belongsTo(Group::class);
}
}
See that I have removed $table from both, as the framework will be able to define the same name as you defined there.
Now, if you want to return a name instead of a group_id on your Resource, you should have it like this (after applying the previous changes):
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubgroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'group_name' => $this->group->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
If you read the documentation, you will see that, after defining a relationship (for example, group method), you can use $model->group and that will return the associated Group model if found, else null. You can also use $model->group() and that will return a Builder so you can do something on that resource (with a builder, not a model class).
In your specific case, you can directly return the object, as you wanted, by doing:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubgroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'group' => $this->group,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}

Laravel how to get back relationships from an array of ids

I have a table called addresses, it has a column name user_ids which is an array of the users who have that same address.
When I request to /api/addresses what it returns is {id:1,name:"lorem", user_ids:[1,2]}. I want it to return the users instead of their ids
this is the addresses model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'coordinates',
'title',
'description',
'user_ids',
];
protected $appends = ['user_ids'];
protected $casts = [
'user_ids' => 'array',
];
public function users()
{
return $this->belongsToMany(User::class,"addresses");
}
}
this is the create_table_addresses
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->id();
$table->string('coordinates');
$table->string('title');
$table->string('description');
$table->json("user_ids");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('addresses');
}
};
addresses controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreAddressRequest;
use App\Http\Requests\UpdateAddressRequest;
use App\Models\Address;
class AddressController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Address::with('users')->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \App\Http\Requests\StoreAddressRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreAddressRequest $request)
{
$address = Address::create($request->validated());
return response()->json($address, 201);
}
/**
* Display the specified resource.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function show(Address $address)
{
return $address;
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function edit(Address $address)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \App\Http\Requests\UpdateAddressRequest $request
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function update(UpdateAddressRequest $request, Address $address)
{
$address->update($request->validated());
return response()->json($address, 200);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function destroy(Address $address)
{
$address->delete();
return response()->json(null, 204);
}
}
My suggestion would be to use the database for this (since you're already using the with('addresses')).
(Documentation for that relationship starts here)
Migration:
Schema::create('address_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('address_id')->unsigned()->index();
$table->foreign('address_id')->references('id')->on('addresses')->onDelete('cascade');
$table->primary(['user_id', 'address_id']);
});
User model:
use App\Models\User;
class Address extends Model {
public function users() {
return $this->belongsToMany(User::class);
}
}
Address model:
use App\Models\Address;
class User extends Model {
public function addresses() {
return $this->belongsToMany(Address::class);
}
}
Now you can use the relationship your application:
$address->users // Get all the users with that address
$user->addresses // Get all the addresses for the user
Address::with('users') // Get addresses with the users as an attribute
User::with('addresses') // Get users with the Address as an attribute
I am assuming that the response comes from a controller so then where you build you response, you need to append the user information.
Maybe something like
User::whereIn('id', [1,2])->get() ...
If you post the controller, then I can tell you exactly where to put this or how to do it better.

Laravel Many to many store to database

I want a system where I connect users with tasks and later I can assign tasks to different users from the amdin panel. My program doesn't work, it doesn't assign tasks to users. Later, I want to make sure that when a user logs in, they can only see their own tasks that an amdin has given them. Please help me what is the problem?!
Create user_task
Schema::create('user_task', function (Blueprint $table) {
$table->id();
$table->foreignId('task_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
Create users
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('avatar')->default('default.jpg');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Create tasks
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('alkalmazott');
$table->string('projekt')->default('-');
$table->string('feladat');
$table->date('hatarido');
$table->timestamps();
});
Task model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use HasFactory;
protected $fillable = [
'alkalmazott', 'projekt' , 'feladat', 'hatarido'
];
public function projects(){
return $this->belongsToMany('App\Models\Project');
}
public function users()
{
return $this->belongsToMany('User', 'user_tasks');
}
}
User model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
use Tasks;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//public function setPasswordAttribute($password) {
// $this->attributes['password'] = Hash::make($password);
//}
public function jogoks(){
return $this->belongsToMany('App\Models\Jogok');
}
public function tasks()
{
return $this->belongsToMany('Task', 'user_tasks');
}
/* Check if the user has a role
* #param string $role
* #return bool
*/
public function hasAnyRole(string $role){
return null !== $this->jogoks()->where('name', $role)->first();
}
/* Check if the user has any given role
* #param array $role
* #return bool
*/
public function hasAnyRoles(array $role){
return null !== $this->jogoks()->whereIn('name', $role)->first();
}
}
Task controller (here i want to upload tasks)
<?php
namespace App\Http\Controllers;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Http\Request;
class TasksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tasks = Task::latest()->paginate(10);
return view('admin.tasks.index',compact('tasks'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.tasks.create', ['users' => User::all()], ['tasks' => Task::all()]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'alkalmazott' => 'required',
'projekt' => 'required',
'feladat' => 'required',
'hatarido' => 'required',
]);
Task::create($request->all());
return redirect()->route('admin.tasks.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function show(Task $Task)
{
return view('admin.tasks.show',compact('Task'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function edit(Task $Task)
{
return view('admin.tasks.edit',compact('Task'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Task $Task)
{
$request->validate([
'alkalmazott' => 'required',
'projekt' => 'required',
'feladat' => 'required',
'hatarido' => 'required',
]);
$Task->update($request->all());
return redirect()->route('admin.tasks.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function destroy(Task $Task)
{
$Task->delete();
return redirect()->route('admin.tasks.index')
->with('success','Product deleted successfully');
}
}
And after i run my upload form, on the phpmyadmin the task has uploaded done but in the user_task table not working. Because its not working i cant display tasks for the users. Thank you for your replies!
You can use attach(), detach() or sync() functions in controller.
For example:
public function store(Request $request){
// ...
$task = Task::create($request->all());
$task->users->attach($request->users); // or you can use sync(), according to your needs and project
// $request->users must be an array like [1,3,10,21,28] etc.
// ...
}

Laravel Unit test fails with custom attributes

I'm trying to write a unit test on my user model that tests if the soft deleted record is still present in the database.
/**
* check if users are soft deleted only
*
* #return void
*/
public function testUserIsSoftDeleted()
{
$user = factory(User::class)->create();
$user->delete();
$this->assertSoftDeleted('users', $user->toArray());
}
This test runs fine until I add a custom attribute to the model.
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use OwenIt\Auditing\Contracts\Auditable;
class User extends Authenticatable implements MustVerifyEmail, Auditable
{
use HasApiTokens, Notifiable, SoftDeletes, HasRoles, \OwenIt\Auditing\Auditable;
protected $guard_name = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password', 'active', 'activation_token', 'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'activation_token'
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The attributes that should be added to the JSON response
*
* #var array
*/
protected $appends = ['md5_email'];
/**
* Convert email address into md5 string
*
* #var string
*/
public function getMd5EmailAttribute()
{
return md5(strtolower(trim($this->email)));
}
}
When I run the test I get the following error.
How do I include custom attributes in the Found array?
To skip md5_email from the query, assign the toArray result to an array and unset the md5_email
Something like
public function testUserIsSoftDeleted()
{
$user = factory(User::class)->create();
$user->delete();
$userInfoArray = $user->toArray()
// This should skip md5_email getting added to the query
unset($userInfoArray["md5_email"])
$this->assertSoftDeleted('users', $userInfoArray);
}
As stated by Cerlin the md5_email attribute in not present in the database, that's why you get the error. You have many options to make the test pass. You might simply unset the md5_email from the user array or, for the sake of clarity, rewrite your test as follow:
/**
* check if users are soft deleted only
*
* #return void
*/
public function testUserIsSoftDeleted()
{
$user = factory(User::class)->create();
$user->delete();
$this->assertSoftDeleted('users', $user->only('id', 'name', 'email'));
}

Undefined property while trying to connect to a laravel powered database

I tried to create middleware to control the access of users, why I created a table roles may I have this error
Undefined property: Illuminate\Database\Eloquent\Builder::$role_name
User model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles(){
return $this->belongsTo('App\Role','role_id','id');
}
public function hasRole($title){
$user_role=$this->with('roles');
if(!is_null($user_role)){
$user_role=$user_role->role_name;
}
return ($user_role==$title)?true:false;
}
}
the middleware create
<?php
namespace App\Http\Middleware;
use Closure;
class create
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next,$Admin,$SuperAdmin)
{
$User=$request->user();
return ($User->hasRole($SuperAdmin)||$User->hasRole($Admin))?$next($request):response(view('errors.401'),401);
}
}
What you what to do is to receive the relation object. You can do it in this way:
public function hasRole($title){
$user_role = '';
if(!is_null($this->roles)){
$user_role=$this->roles->role_name;
}
return ($user_role==$title)?true:false;
}
The with(...) statment is useful for receiving relation when you're working on collection of elements (eager load constraint).

Categories