Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: conflict between model name and built-in facade

I have a Model in my Laravel app called Event. As I just discovered, this creates a conflict between my model and Illuminate\Support\Facades\Event, a built-in facade. The obvious solution here is to either change the name of my Model, which is not ideal because there is really no other name I could give my Model that makes any sense, or to rename the alias in app.php for Illuminate\Support\Facades\Event, which I'd like to avoid for fear of breaking anything that may rely on that alias in the future (I'm afraid I may forget).

It's been suggested that perhaps I could use namespaces, which I attempted as follows:

app/models/Event.php

namespace Models; #<-- I've also tried using "\Models" here

class Event extends \Eloquent{

app/database/seeds/DatabaseSeeder.php

Models\Event::create();  #<-- again, I've also used "\Models\Event"

All 4 combinations above have yielded a Class 'Models\Event' not found error when I run php artisan db:seed.

Perhaps I simply don't understand namespaces properly, but the more pressing issue is how to solve my problem. If it can be solved using namespaces as suggested, great, but I'm open to any other ideas as well.

like image 568
ewok Avatar asked Oct 01 '22 04:10

ewok


1 Answers

I made this mistake early on as well, not necessarily understanding the role of namespace throughout the entire app.

The namespace should mark the business logic within the domain or responsibility of the app itself, so giving a namespace of Models isn't necessarily useful. Instead create a root namespace named after the app, your company, you, or whatever you like, then provide a Model sub-namespace.

For example:

namespace MyGreatApp\Models;

class Event extends \Eloquent{ }

Then you would reference this model under:

use MyGreatApp\Models\Event;

$event = new Event();

In the long run this is a cleaner and more organized approach. This does mean moving your models into a different folder, though. But there's nothing wrong with that. At least that way you know you have all your custom code in your MyGreatApp namespace. :)

like image 72
mike.bronner Avatar answered Oct 03 '22 18:10

mike.bronner