How to get list of permissions in a role - laravel-5

I'm using Romanbican/Roles laravel package, and I have permission_role table, roles table, and permissions table. Now, I want to get all permissions of a specific role. e.g. (role: Admin, permissions: create.users, delete.users, edit.users. The result would be:
Admin:
create.users
delete.users
edit.users
how can I do that? Here's my tables with fields:
roles
id | name | slug | level |
permissions
id | name | slug |
permission_role
id | permission_id | role_id |

First of all, you'll need a controller to handle this. The controller must be able to get the role, then it needs to look after the perms by the role and then get the permissions.
So it would look something like this;
public function editRolePerms($id)
{
$getrole = Role::findOrFail($id);
$permbyrole = DB::table('permission_role')->select('permission_id')->where('role_id', $id)->lists('permission_id');
$getperms = Permission::all();
return view('your_view')->with('role', $getrole)->with('getperms', $getperms)->with('permbyrole', $permbyrole);
}
That would be the controller, then to get the perms by the roles in your view, it would look something like this:
#foreach($getperms as $perm)
<tr>
<td>{{ $perm->name }}</td>
<td>{{ $perm->description }}</td>
#if(!in_array($perm->id, $permbyrole))
<td><span id="{{ $perm->id }}" class="label label-danger">Not enabled</span></td>
<td><input onclick="toggleRole({{ $perm->id }}, {{ $role->id }})" type="checkbox" id="checkbox_{{ $perm->id }}"></td>
#else
<td><span id="{{ $perm->id }}" class="label label-success">Enabled</span></td>
<td><input onclick="toggleRole({{ $perm->id }}, {{ $role->id }})" type="checkbox" checked="true" id="checkbox_{{ $perm->id }}"></td>
#endif
</tr>
#endforeach
Hope this suits your need.

Make relationship in Role model file
public function permissions()
{
return $this->belongsToMany(Permissions::class, 'permission_role', 'role_id', 'permission_id ')
}

Related

How to convert multiple staff id to name in laravel?

This is my index page where I want to get name by ids. if there is single id in Staff_id column than it show but if their is multiple id than it only show first one
#foreach($assignments as $assignment)
<tr>
<td>
<form action="{{ route('assignments.complete', $assignment->id) }}" method="post">
#csrf
#if ($assignment->done_at == null or $assignment->done_at = '')
<button type="submit" name="submit">incomplete</button>
#elseif ($assignment->done_at !== null)
<button type="submit" name="submit">Complete</button>
#endif
</form>
</td>
<td>{{$assignment->id}}</td>
<td>
{{$assignment->staff->name}}
</td>
<td>{{$assignment->task->title}}</td>
<td>{{$assignment->task->description}}</td>
<td>{{$assignment->task->done_at}}</td>
<td>{{$assignment->task->created_at}}</td>
<td>
<form action="{{ route('assignments.destroy',$assignment->id) }}" method="post">
#csrf
#method('delete')
<button class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
It showing like this``
In your Blade file first, you need to convert string to array
#php
$staff = $assignment->staff_id;
$staff_ids = explode(",",$staff_name); //converted to array
print_r($staff_ids); //here you can check
#endphp
<td>
#foreach ($staff_ids as $value)
{{ $loop->first ? '' : ', ' }}
<span class="nice">{{ $value->name }}</span>
#endforeach
</td>
Personally id write a mutation on the assignment model, e.g.
getStaffNameAttribute()
{
return $this->staff()->first()->name;
}
which can be used like so
$assignment->staffName
but you could just do
$assignment->staff->first()->name;
I may be missing parenthesis in this.
Also this is only if you actually made them related... and not just manually entered in ID's in a column.... which i have a feeling you did...
EDIT
Showing how the many relation works.
On the assignment model you would have this
public function staff()
{
return $this->belongsToMany(Staff::class);
}
and on the staff model you would have
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
This relation would require a pivot table called assignment_staff with assignment_id and staff_id How you name the pivot tables are alphabetical order with singular names e.g. A comes before S so its assignment_staff not staff_assignment.
The reason its many to many as one assignment can have many staff and each staff can belong to many assignments.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

Missing required parameters for [Route: addapplication.edit]

I'm having trouble on passing application_id from application#edit controller to addapplication#index controller. Please help me.
application#edit controller
$application->application_id = $request->application_id;
$application->save();
return redirect(route('addapplication.index'))->with('application_id',$request->application_id);
addapplication#index controller
$application_id = Session::get('application_id');
$applications = addapplication::where('application_id', $application_id)->get();
return view('user.addapplication.index',compact('applications'));
blade.php
#foreach ($applications as $application)
<tr>
<td>{{ $loop->index +1 }}</td>
<td>{{ $application->application_id }}</td>
<td>{{ $application->created_at }}</td>
<td>{{ $application->surname }}, {{ $application->firstname }} {{ $application->middlename }}</td>
<td><img src = {{ asset('assets/img/eye.ico') }}/>
</td>
</tr>
#endforeach
I'm getting this error:
Missing required parameters for [Route: addapplication.edit] [URI:
addapplication/{addapplication}/edit]. (View: D:\path\index.blade.php)
here is my route.php
Route::resource('application', 'ApplicationController');
Route::resource('addapplication', 'AddApplicationController');
Please help me. Thank you!
You have to use like this
{{route('addapplication.edit',['addapplication'=>$application->id])}}
The route helper requires an array as the secondary argument.
{{ route('addapplication.edit', ['addapplication' => $application->id])}}
You can figure out the required key (in any scenario) by using the artisan route:list command and looking at the values between the curly braces in the URI column.
In your case the route should look like this:
/addapplications/{addapplication}/edit

Level 7 display relationship data in blade using one to many

whats wrong why in blade don't want to show the LEVEL name
controller:
$streams=Stream::with('level')->get();
return view('streams.index',compact('streams'));
Stream Model:
public function level()
{
return $this->belongsTo('App\Models\Level', 'level_id');
}
Level Model:
public function stream()
{
return $this->hasMany('App\Models\Stream', 'level_id');
}
Blade Index:
#foreach($streams as $stream)
<tr>
<th scope="row">#</th>
<td>{{$stream->name}}</td>
<td>{{$stream->code}}</td>
<td>
{{$stream->level->name}}
</td>
<td>
<tr/>
#endforeach
Also tried:
#foreach($streams as $stream)
<tr>
<th scope="row">#</th>
<td>{{$stream->name}}</td>
<td>{{$stream->code}}</td>
#foreach($stream as $level)
<td>
{{$level->name}}
</td>
#endforeach
<td>
<tr/>
#endforeach
Error:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\project\sms\resources\views\streams\index.blade.php)
DD result:
[{"id":3,"name":"Class A","code":"GRC0001A","uuid":"X9HG9zc7ceTlhdfF1fN1wAer1cHP1MhfuM7GHBSqNogYSo3bsGmpTl06iJQyyKp3QMrkHe1VyiTxeKFa49wC7W5BY3E3kFZkpF1D","level_id":1,"created_at":"2020-06-14T10:58:28.000000Z","updated_at":"2020-06-14T11:39:54.000000Z","level":{"id":1,"name":"YEAR 7","code":"CODE1","uuid":"X9HG9zc7ceTlhdfF1fN1wAer1cHP1MhfuM7GHBSqNogYSo3bsGmpTl06iJQyyKp3QMrkHe1VyiTxeKFa49wC7W5BY3E3kFZkpF1D","created_at":"-000001-11-30T00:00:00.000000Z","updated_at":"-000001-11-30T00:00:00.000000Z"}},{"id":4,"name":"Class B","code":"GRC0001A","uuid":"gq2kZZikN76XEa4pQWsyAZBMxjKeHBJt0a840ZMSiuHGztuhYT0G6q5WcGgp8z6BD6nx0WSrrOTvEb4iQ0ewyB9Fa1M54CAv8HS2","level_id":null,"created_at":"2020-06-14T10:58:36.000000Z","updated_at":"2020-06-14T11:39:59.000000Z","level":null}]
Your first Blade template is almost correct.
The issue is that one or more of your records has no Level assigned (level_id=null), but you're still trying to pull the name property from $stream->level, which is null.
Simply add a check for $stream->level before trying to access/print its properties. For example:
#if($stream->level)
{{ $stream->level->name }}
#endif
or
{{ $stream->level ? $stream->level->name : 'No Level Attached' }}
or
{{ optional($stream->level)->name }}
etc.

nested foreach loop break in laravel

I am working with laravel. I have two table. one is users and another is permission. I have two foreach loop. One is to show user data. User data coming from users table. And another foreach loop is is for checking is that user available or not in permission table.
I am fetching all user from users table like this:
$allTeachers = User::where('role',2)->paginate(4);
And am also fetching all data from permission table like this.
$allpermiteds = Specialpermission::where('add_teacher','!=','NULL')->get();
I have sent those two query to my view. And it is working fine.
Now I am printing those users data in my view like this
#foreach($allteachers as $teacher)
<tr>
<td>{{ $teacher->id}}</td>
<td>{{ $teacher->name }}</td>
<td>{{ $teacher->email }}</td>
<td><button>give</button></td>
<td><button>Remove</button></td>
#endforeach
I have printed two button there give and remove. Now I want to do that, If $teacher->id is available in the permission table add_teacher column then it should show remove button. Otherwise it should Show add button.
I have done like this, But it is not working properly.
#foreach($allteachers as $teacher)
<tr>
<td>{{ $teacher->id}}</td>
<td>{{ $teacher->name }}</td>
<td>{{ $teacher->email }}</td>
<td>#foreach($allpermitted as $p)
#if($p->add_teacher == $teacher->id)
<button>Remove</button>
#else
<button>give</button>
#endif
#endforeach</td>
#endforeach
It shows a lot of button. If there are 4 users in the permission table then it will show 4 button for each user. That is the main problem
Thanks in advance.
Simple, select add_teacher column from db, then convert your Specialpermission objects into array like below:
$permissionData = Specialpermission::where('add_teacher','!=','NULL')->select('add_teacher')->get();
$allpermiteds = collect($permissionData )->map(function($x){ return (array) $x; })->toArray();
Then use in_array to check for permission check
#foreach($allteachers as $teacher)
<tr>
<td>{{ $teacher->id}}</td>
<td>{{ $teacher->name }}</td>
<td>{{ $teacher->email }}</td>
<td>
#if(in_array($teacher->id,$allpermitted))
<button>Remove</button>
#else
<button>give</button>
#endif
</td>
#endforeach
I prefer using the eloquent function with that defines the relationship between the two tables:
$allTeachers = User::where('role',2)->with('SpecialPermisson')->paginate(4);
It will add a field of SpecialPermission (if it has). If not, it will give you a blank field, so check if its empty.

Laravel with Revisionable Package and catching errors

Using Laravel and Revisionable package. I am populating a table with user record modifications and have the following code snippet:
<tr>
<td width="150">{{ $revision->updated_at }}</td>
<td>User</td>
<td>{{ $revision->revisionable->first_name }} {{ $revision->revisionable->last_name }}</td>
<td width="50">{{ $revision->fieldName() }}</td>
<td width="50">{{ $revision->userResponsible()->first_name }}</td>
<td>{{ $revision->oldValue() }}</td>
<td>{{ $revision->newValue() }}</td>
</tr>
Getting the users first and last name works fine when the original user record exists but in some cases the original record (user) is deleted and it causes an error because the user record no longer exists. Is there an IF Statement I can use to first check if the first name field returns an error? Then I can display first/last name for records that still exist and something else if it doesn't exist.
Thanks in advance!
Blade has the orsyntax, really nice:
{{ $revision->revisionable->first_name or 'N/A'}}
{{ $revision->revisionable->last_name or 'N/A'}}
alternatives, though not as elegant:
{{ isset($revision->revisionable->first_name) ? $revision->revisionable->first_name : 'N/A' }}
or
#if (isset($revision->revisionable->first_name))
{{ $revision->revisionable->first_name }}
#else
N/A
#endif

Resources