0
votes

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.

2
I’m a bit confused. When do you have {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
No, it creates a subfolder inside that {folder}. Originally the route was users/{user}/folders/{folder}/folders but I renamed it to check if that had something to do with the problem.JDLK7

2 Answers

3
votes

Get the parameter using:

$this->route('parameterName');

or

$request->route('parameterName');
-1
votes

If you are passing parameters into route then it could not be a POST request its get its called urlencoded format.

If you dont know about it simply use any keyword instead of post and get laravel set it to appropriate check the manual first route methods

use any method like this,

Route::any('users/{user}/folders/{folder}', 'FileController@listUserFolder');

I hope it helps.