JDLK7
JDLK7

Reputation: 59

Route Model binding not working with POST

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.

Upvotes: 1

Views: 1610

Answers (2)

Mahdi Younesi
Mahdi Younesi

Reputation: 7489

Get the parameter using:

$this->route('parameterName');

or

$request->route('parameterName');

Upvotes: 3

Ritesh Khatri
Ritesh Khatri

Reputation: 1301

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.

Upvotes: -1

Related Questions