Autoload of Models in Laravel 5.1

Asked

Viewed 506 times

2

Good night I wonder if in Laravel 5.1 there is a way to autoload, both in Models and Controllers? In Laravel 4 to create an instance of a Model, simply call the Model, thus:

$user = new User();

But from what I noticed on Laravel 5, you need to put the model’s path into the controller.

  • Ever tried to spin composer dump-autoload?

  • In Laravel 5 you need to call by the p.x namespace: App Models User;! Unless you create an alias in app.php. It is also possible to make the class map by Composer, psr-4

2 answers

1

You have to use use and the way to models ou controllers,

example:

File Productocontroller.php, I’m getting the model Product like this:

 use app\Produto;

1

The autoload is still there, it just depends on how you want to call the class

Normal

namespace App\Http\Controllers;

class UsersController extends App\Http\Controllers\Controller {

    public function create() {
        $user = new App\User;
    }

}

Or by creating an alias

Aliasing

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UsersController extends Controller {

    public function create() {
        $user = new User();
    }

}

To review the basics of Laravel 5, I recommend seeing https://laracasts.com/series/laravel-5-fundamentals is free.

  • So, but in version 4 you didn’t have to put "use App User" for every Model you called. That’s what I wanted to know, you know? If there’s any way you don’t have to put this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.