0
votes

I am trying to set up middleware. I followed these instructions:

http://mattstauffer.co/blog/laravel-5.0-middleware-filter-style

And my code is

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\RedirectResponse;

class LoadVars {

$comingevents = App\Number::where('item','events')->get(array('quantity'));

I got this error:

FatalErrorException in LoadVars.php line 24: Class 'App\Http\Middleware\App\Number' not found

In models when I define relations I use App\Number and it works well.

What is the proper way of using Classes inside a middleware method?

1
You have specify the absolute namespace by prefixing it with a backslash: \App\Number, otherwise it will be interpreted relative to the namespace you are currently in, which is App\Http\Middleware. Or you could use App\Number; at the top and then just access it with Number::where(...);Quasdunk
Thank you for the tip. It helped me to get orientation in the new L5 namespace rules.Peter

1 Answers

2
votes

As @Quasdunk pointed out right in the comments, when you reference a class without backslash at the beginning, the path is relative.
Meaning App\Number will look in the current namespace for App and then Number.

App\Http\Middleware  &  App\Number   =>  App\Http\Middleware\App\Number

You just have to add a \ at the start and the path will be interpreted absolute and it actually doesn't matter from where you are using the class

App\Http\Middleware  &  \App\Number  =>  App\Number
Foo\Bar              &  \App\Number  =>  App\Number

If you like your code a bit cleaner you can also import the class with a use statement:

use App\Number;

class LoadVars {
    // ...
    $comingevents = Number::where('item','events')->get(array('quantity'));
    // ...
}

Note that with the use statement there's no need for the backslash. All paths will be absolute.