jackchmbrln
jackchmbrln

Reputation: 1713

Laravel - check request method

I'm an iOS lead on an app and trying to fix some API bugs whilst our dev is 'unavailable'. I'm almost completely new to Laravel and trying to check what the request method is. I have followed some guidance from another question but have been unable to get it working:

public function defaults(Request $request, User $user){
    $follow_ids = explode(',', env('FOLLOW_DEFAULTS'));

    if ($request->isMethod('post')) {
        return ['user' => $user];
    }

    $user->follows()->syncWithoutDetaching($follow_ids);

    return ['user.follows' => $user->follows->toArray()];
}

Do you know where I might be going wrong here? Thanks in advance.

When the request is returned it always just seems to skip over and return ['user.follows' => $user->follows->toArray()]

Upvotes: 6

Views: 38774

Answers (2)

patricus
patricus

Reputation: 62338

$request should be an instance of Illuminate\Http\Request. This class extends Symfony's request (Symfony\Component\HttpFoundation\Request), which is actually where the isMethod() method is defined.

Basically, given the function definition as posted, it reads "if this is a POST request, just return the user data. if this is not a POST request (e.g. GET), update and return the relationship data."

So, if you send a POST request, you'll get the ['user' => $user] response. If you send any other request method (e.g. GET), you'll modify the follows relationship and get the ['user.follows' => $user->follows->toArray()] response.

To me, this seems backwards. I would think you'd want the POST request to update the data, and any other request (e.g. GET) to just return data.

If this is correct, you need to negate your isMethod check:

if (! $request->isMethod('post')) {
    return ['user' => $user];
}

More appropriately you should define separate controller actions to handle POST vs GET requests, but that is outside the scope of this question, and probably more than you want to get into as a temporary maintainer.

Upvotes: 16

aletzo
aletzo

Reputation: 2456

It seems that the request is not a POST so the if check is never true. You could echo the method name like this:

$method = $request->method();

echo $method; 

// or var_dump($method);

Upvotes: 6

Related Questions