Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - check request method

Tags:

php

laravel

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()]

like image 477
jackchmbrln Avatar asked Aug 24 '26 15:08

jackchmbrln


1 Answers

$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.

like image 131
patricus Avatar answered Aug 27 '26 06:08

patricus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!