Using models on packages
Asked Answered
A

3

5

I'm trying to use Laravel packages. I created MyVendor/MyPackage

Routes, controllers, filters are already working. This is the classmap of my package:

"classmap": [
        "src/migrations",
        "src/controllers",
        "src/seeds",
        "src/models"
    ],

This is how looks my model:

namespace MyVendor\MyPackage\Models;             
class MyModel extends \Illuminate\Database\Eloquent\Model {   
}

And this is the code inside my controller which is in namespace MyVendor\MyPackage.

$test = new models\MyModel;      

I'm getting this error: Class 'MyVendor\MyPackage\models\MyModel' not found

I can't figure out why. I'm new with namespaces so maybe it is something related to this. I tried with composer update, composer dump-autoload (inside my package) and still can't find my models.

If I get the declared classes with get_declared_classes() I can't see my model there.

The problem is that my model classes are not autoloading.

Akanke answered 2/10, 2013 at 8:37 Comment(1)
Are you sure you are using matching case for namespace? Your error has models with a lowercase m whereas your namespace declares it uppercase.Trisa
P
8

Try this:

  1. Create models directory inside your package and add it to the package's classmap
  2. Add a model YourModel.php with the following:

    <?php
    // Note no namespace
    
    use \Illuminate\Database\Eloquent\Model as Eloquent;
    
    class YourModel extends Eloquent {
        //
    }
    
  3. Run composer dump-autoload from your package directory first and then root directory
  4. Test your model by putting this at the top of your routes.php file:

    <?php
    $testModel = YourModel::get();
    die(var_dump($testModel));
    ?>
    
Peluso answered 2/10, 2013 at 17:30 Comment(2)
Minor hint: Laravel has the helper function dd (); Use this instead of die(var_dump()). laravel.com/docs/4.2/helpers#miscellaneousAstragal
@KoenBetsens Yes, but only if you prefer the output of dd(). :-)Peluso
L
0

These works for me on Laravel 4.2

<?php namespace Vendor\Package;

use \Illuminate\Database\Eloquent\Model as Eloquent;

class Product extends Eloquent {

    ...

}
Lambard answered 7/10, 2014 at 12:3 Comment(0)
P
0

In my case, running composer dump-autoload solved the problem. Remember, once you change the model, run composer dump-autoload again.

laravel version: 10, code:

namespace vendor\package\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class name extends Model
{
    use HasFactory;
}
Piane answered 1/2 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.