Skip to content
Advertisement

how to load Laravel 6 model classes without namespace

I am new to Laravel and I was working on Laravel 4. I am trying to migrate to Laravel 6 on docker and I have the basic setup and Laravel project is up.

I created a table and a respective Eloquent Model in the models folder. I am able to read the data in a controller.

namespace AppHttpControllers;

use mysql_xdevapiException;
use  AppModelsCard;

class welcomeController {
    public function show() {
        try {
            $cards = Card::all();
        } catch (Exception $e) {
            die("Could not connect - " . $e );
        }

        print_r($cards); exit;
    }
}
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Card extends Model
{

}

In the older version of Laravel project, the ‘Card::all()’ was working without using USE command to import it.

I know namespaces are important, but wondering how it worked and how I can make replicate the same.

Advertisement

Answer

I do not know why you want to discard using namespaces, If you want to NOT use namespaces for your models, edit your composer.json like below

"autoload": {
    "psr-4": {
        "App\": "app/"
    },
    "classmap": [
        "database/seeds",
        "database/factories",
        "models"
    ]
},

Make a directory in your root directory and add a new file i.e ‘models/Card.php’.

below should be the content of your Card.php

<?php 

use IlluminateDatabaseEloquentModel;

class Card extends Model {

    //database table here
    protected $table = "cards";

    //Fillables
    protected $fillable = [];
    
}

And in your controller WelcomeController

<?php

namespace AppHttpControllers;

use mysql_xdevapiException;

class welcomeController {
    public function show() {
        try {
            $cards = Card::all();
        } catch (Exception $e) {
            die("Could not connect - " . $e );
        }

        print_r($cards); exit;
    }
}

Do not forget the forward slash in your card model i.e ‘Card::all()’

Make sure to move your models folder outside the app directory, Kindly note this is not php best practice

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement