The problem is undefined offset when i try to show all posts with permissions. Without Encode and Decode the links this problem never been happened. When i encode and try to pass the encode links to edit post, it's no problem. but when i try to show all post, the problem was happened and show me undefined offset [0]. How to fix this problem??
My controller to edit post
public function edit($id)
{
$key = Hashids::connection('main')->decode($id)[0] ?? abort(404);
$post = Post::findOrFail($key);
$tags = Tag::all();
$tags2 = array();
foreach($tags as $tag){
$tags2[$tag->id] = $tag->name;
}
return view('dashboard.adminblogpost.editpost', compact('post','tags2'));
}
my view
@php $parameter = Hashids::connection('main')->encode($post->id); @endphp
@if(check_user_permissions($request, "BlogPost@edit", $parameter))
<a href="{{route('admins-blogpost.edit', $parameter)}}" class="btn btn-xs btn-warning">
<i class="fa fa-edit"></i>
</a>
@else
<a href="#" class="btn btn-xs btn-warning disabled">
<i class="fa fa-edit"></i>
</a>
@endif
and method for check permission
<?php
use Vinkla\Hashids\Facades\Hashids;
function check_user_permissions($request, $actionName = NULL, $id = NULL)
{
$currentUser = $request->user();
if($actionName)
{
$currentActionName = $actionName;
}
else{
$currentActionName = ($request->route()->getActionName());
}
list($controller, $method) = explode('@', $currentActionName);
$controller = str_replace(["App\\Http\\Controllers\\Backend\\", "Controller"], "", $controller);
$crudPermissionsMap = [
'crud' => ['create', 'store', 'edit', 'update', 'destroy', 'restore', 'forceDestroy', 'index', 'view']
];
$classesMap = [
'BlogPost' => 'post',
'CategoriesPost' => 'category',
'Users' => 'user'
];
foreach($crudPermissionsMap as $permission => $methods){
if(in_array($method, $methods) && isset($classesMap[$controller]))
{
$classesName = $classesMap[$controller];
// dd("{$permission}-{$classesName}");
if($classesName == 'post' && in_array($method, ['edit', 'update', 'restore', 'destroy', 'forceDestroy']))
{
$id = !is_null($id) ? $id : $request->route("admins_blogpost");
if( $id
&& (!$currentUser->can('update-others-post') || !$currentUser->can('delete-others-post')))
{
$post = \App\Post::withTrashed()->find(Hashids::decode($id)[0]);
if($post->author_id != $currentUser->id){
return false;
}
}
}
elseif(! $currentUser->can("{$permission}-{$classesName}")){
// abort(403, "forbidden access!");
return false;
}
break;
}
}
return true;
}
</div>