Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Remove Parameter From All Request Objects at Controller Level

I have URLs that look like:

http://example.com/api/user?id=45&name=mike&api_token=2348283
http://example.com/api/project?id=5&description=first&api_token=2348283
etc...

In my controllers, I have functions that look like:

public function user_get_endpoint(Request $request){

    $request = $request->toArray();
    return UserModel::where($request)->get()->toArray();

}

The above will currently break since the $request object contains a property called api_token which does not exist in the user table. I am using the api_token in a middleware to check for authentication.

I can manually unset the api_token property in each of my API functions by using unset($request['api_token'], but I'd like to avoid that if possible.

Is there anyway to do this application wide or at a class or controller level?

like image 973
Lloyd Banks Avatar asked Oct 28 '16 19:10

Lloyd Banks


3 Answers

Laravel provides add and remove functions to add and remove new properties to the request object respectively.

 $request->request->add(['api_token' => 'api_token']); // to add new property to $request
    $request->request->remove('api_token'); // to remove property from $request
like image 188
Shams Reza Avatar answered Oct 13 '22 21:10

Shams Reza


Perhaps you want global middleware?

First arrange for the middleware to run on all routes:

// routes.php
$app->middleware([
    App\Http\Middleware\Apitoken::class
]);

Then define what the middleware should do:

// src/App/Http/Middleware/Apitoken.php
<?php
namespace App\Http\Middleware;

use Closure;

class Apitoken
{
    public function handle($request, Closure $next)
    {
        unset($request['api_token']);

        return $next($request);
    }
}
like image 21
bishop Avatar answered Oct 13 '22 20:10

bishop


Method 1

$request->except(['key1','key2',....])

provides an easy way to skip unwanted keys, similarly

Method 2

$request->only(['key3','key4',....])

provides an easy way to skip all others unwanted keys, I find both reasonably good for almost all scenarios

like image 23
justnajm Avatar answered Oct 13 '22 21:10

justnajm