Jesús Cova
Jesús Cova

Reputation: 51

The custom middleware is not working in the controller (Laravel)

I did a custom middleware to handle the auth api token and I call this middleware in the controller, but it's not working I added dd('') inside the middleware to see if it displays anything and it did not worked.

My middleware is:

<?php

namespace App\Http\Middleware;

use Closure;

use App\ApiUser;

class ApiAuth
{
/**
 * Run the request filter.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next, $var)
{
   dd('If I put this dd it does not display anything');

    $api_user_count = ApiAuth::where('api_token', $var)->count();

    if($api_user_count == 0)
    {
        abort(403, "Auth failed")
    }
    
    return $next($request)
 }
}

My controller is, how you can see I am sending a parameter to the middleware:

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->middleware('apiauth:'.$request->api_token);

    $transaction = new Transaction;

    $transaction->folio = $request->folio;

    $transaction->dte_code = $request->dte_code;

    $transaction->cashier = $request->cashier;

    $transaction->amount = $request->amount;

    if($transaction->save())
    {
        return response()->json('Ok', 201);
    }
    else
    {
        return response()->json('Error', 400);
    }
}

I put the middleware in the path App\Http\Middleware\ApiAuth.php

I put the middleware in the kernel.php like this:

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'apiauth' => \App\Http\Middleware\ApiAuth::class, // THIS IS THE MINE
];

The weird thing is that it does not display any error, it's like it does not exist so I wonder what it's wrong with this?

Thanks!

Upvotes: 0

Views: 425

Answers (1)

sazzad
sazzad

Reputation: 525

instead of calling the middleware manually from your controller method you can register the middleware to apply only for that one method

public function __construct()
{
    $this->middleware('apiauth')->only(['store']);
}

then you can extract the api_token from $request

$api_user_count = ApiAuth::where('api_token', $request-> api_token)->get()->count();

Upvotes: 1

Related Questions