Skip to main content

Editor Endpoint: Update Travel

Premium
4:15

Comments & Discussion

M
maxralph01 ✓ Link copied!

Hi Povilas || Anyone else who sees this and can help,

I have a project where I am trying to use the comma seperated value to determine where multiple roles ('super-admin' and 'admin' roles, in this case) should have access to a particular route. Unfortunately, only one role (at a time) is going through, not more than one.

My test for this feature, keeps failing.

Here are my codes below.

Kindly help urgently. Thanks in advance.

C:...\tests\Feature\CategoryTest.php

public function test_admin_can_retrieve_categories()
{
// $ADMIN_ROLE = 2;
$admin = User::factory()->create(['role_id' => Role::ADMIN_ROLE]);
 
$response = $this->actingAs($admin)->getJson('/api/v1/admin/categories');
 
$response->assertStatus(200);
}

C:...\app\Http\Middleware\RoleMiddleware.php

public function handle(Request $request, Closure $next, string $roles): Response
{
if (!auth()->check()) {
abort(401);
}
 
$roles_array = explode('|', $roles);
 
foreach ($roles_array as $role) {
if (!auth()->user()->role()->where('name', $role)->exists()) {
abort(403);
}
}
 
return $next($request);
}

C:...\routes\api.php

Route::middleware(['auth:sanctum'])->group(function () {
 
Route::prefix('admin')->group(function () {
 
...
 
Route::middleware(['role:super-admin|admin'])->group(function () {
Route::apiResource('categories', Admin\CategoryController::class)->except(['store', 'update', 'destroy']);
});
 
...
});
});
H
hrsa ✓ Link copied!

I think the problem is in your middleware. Since you use foreach - you're basically saying "if user doesn't have one of the roles in the array - abort".

I'd rather compare the arrays of current user role and the allowed roles :

$roles_array = explode('|', $roles);
 
$userRoles = auth()->user()->roles()->pluck('name')->toArray();
 
$allowedRoles = array_intersect($userRoles, $roles_array);
 
if ($allowedRoles === []) {
abort(403);
}
M
maxralph01 ✓ Link copied!

Thanks for your reply. I have already concluded the app using a verbose pattern.

I will apply your pattern in my next project that is coming up this month.

A
andywong31 ✓ Link copied!

Povilas, is there a way for the slug value to also be updated whenever we update the name value?

PK
Povilas Korop ✓ Link copied!

Yeah, you could create an Observer with updating() or updated() method for this, I guess.

A
andywong31 ✓ Link copied!

Also, since this is the requirement from the client:

A private (editor) endpoint to update a travel;

Why is admin also able to update a travel? shouldn't it be only the editor who's allowed to update?

PK
Povilas Korop ✓ Link copied!

Tell that to the client :)

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.