jason
jason

Reputation: 117

Laravel 5 preventing 'use'

Is there a way to prevent using 'use' for everything. In Laravel 4 I never used 'use' and everything just worked. I'm now finding out I have to include everything, even 'DB' use DB. This is extremely frustrating and time consuming looking all this up.

My question is, is there an easier way to include everything?

<?php 
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Customer;
use DB;

class HomeController extends Controller {

}
?>

Thanks

Upvotes: 2

Views: 428

Answers (2)

Gordon Oppenheimer
Gordon Oppenheimer

Reputation: 143

This is question is old but I found you can do this based on information from a tutorial by Tejas Jasani: http://www.theappguruz.com/blog/upgrading-from-laravel-4-2-to-5-in-web

Here are the key steps:

1 - Add the app/Http/Controllers directory to the "autoload" classmap directive of your composer.json file.

"autoload": {
    "classmap": [
        "database",
        "app/Http/Controllers"
    ],

2 - Remove the namespace from the abstract app/Http/Controllers/Controller.php base class.

3 - In app/Providers/RouteServiceProvider.php file, set the namespace property to null

protected $namespace = null;

4 - Run "composer dump-autoload" from the command line.

Upvotes: 0

Alana Storm
Alana Storm

Reputation: 166066

Not really -- this is the Brave New Namespaced world of PHP 5.3+. Your class file above lives in the App\Http\Controllers namespace, which means when you type something like

$object = new SomeClass;

PHP will assume you mean the class App\Http\Controllers\SomeClass.

You'll either, as you complained about, need to use use, or you'll need to use the full classname (with a leading \ to let PHP know to start from the global namespace) whenever you want to use a class

class HomeController extends Controller {
    public function someFunction()
    {
        $result = \DB::query(...);  
        $customer = new \App\Models\Customer;
        //etc...
    }
}

Upvotes: 2

Related Questions