Skip to main content

Editor Endpoint: Update Travel

Premium
4:15
maxralph01 avatar

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']);
});
 
...
});
});
hrsa avatar

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);
}
maxralph01 avatar

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.

andywong31 avatar

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

Povilas Korop avatar

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

👍 1
andywong31 avatar

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?

Povilas Korop avatar

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.