Ad

Laravel Middleware Use Carbon

- 1 answer

I have middleware where I need to restrict user access if certain date has passed but the functionality doesn't work as expected

Code

class PaidMiddleware
{
    public function handle($request, Closure $next)
    {
        $invoices = Invoice::where('paid', false)->get();
        $now = Carbon::today();
        foreach($invoices as $invoice){
            if(Auth::id() == $invoice->user_id && $invoice->end->isAfter($now)){
                return redirect()->route('forbidden');
            } else {
                return $next($request);
            }
        }
        return $next($request);
    }
}

Logic

  1. If Auth user id is same as user_id column in invoices table
  2. and if invoice row isn't mark as paid
  3. then check end column and if that date is passed redirect user to forbidden page, otherwise let him/her do their activities.

Question

Which part of my code I did mistake?

Noteend column is date and not dateTime could that be the issue?

Ad

Answer

Try to remove that else condition, not sure if that was your problem

class PaidMiddleware
{
    public function handle($request, Closure $next)
    {
        $invoices = Invoice::where('paid', false)->get();
        $now = Carbon::today();
        foreach($invoices as $invoice){
            if(Auth::id() == $invoice->user_id && $invoice->end->isAfter($now)){
                return redirect()->route('forbidden');
            }
        }
        return $next($request);
    }
}
Ad
source: stackoverflow.com
Ad