I have two HTTP methods for the same route as shown below:
Route::group(['middleware' => ['user.ownership']], function () {
Route::get('users/{user}/folders/{folder}', 'FileController@listUserFolder');
Route::post('users/{user}/folders/{folder}/folders', 'FileController@createFolder');
});
The problem is that when the request hits the middleware user.ownership
the route model binding works for the GET request but does not work for the POST. It makes no sense to me.
The middleware checks if the user owns the resource (in this case a folder). The problem shows up when I try to get the Folder
model. In one case it returns the model but in the other it just returns the id. Here's the middleware code:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckIfUserOwnsResource
{
/**
* Comprueba si el recurso solicitado pertenece
* al usuario que lo solicita.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$user = $request->user();
$file = $request->folder;
$fileOwner = $file->account;
$fileApplicant = $user->account;
if($fileOwner != $fileApplicant) {
return response()->json([
'success' => false,
'message' => 'El recurso no le pertenece',
], 403);
}
return $next($request);
}
}
EDIT
The POST route creates a subfolder inside the folder passed.
{folder}
in your POST route if a user’s creating a folder? The folder doesn’t exist if the user’s creating it? – Martin Bean{folder}
. Originally the route wasusers/{user}/folders/{folder}/folders
but I renamed it to check if that had something to do with the problem. – JDLK7