Simon Davies Digital ltd

Namespacing Models in Laravel

Posted by & filed under Laravel, PHP.

I have been using Laravel quite a bit recently and it’s a great framework, which is really good fun to code with. I’ve just started writing a registration system in Laravel and came across a problem which I felt was worth sharing. I was creating the table and model to store the event details and I found that the Event class caused a conflict with one of Laravel’s core libraries. The easy work around is to append _model┬áto the model name. But this detracts from laravel’s expressive syntax, for example:

Event::find(1);

Is much more elegant than:

Event_model::find(1);

This is where namespaces come in, namespaces are a great way to group code to prevent naming collisions. All I do is define a Models namespace at the top of the model.

Namespace Models;
use Eloquent; // If your model extends Eloquent you will need this line

And then in each of the controllers that I need to use a model just add this line at the top of the file

use Models\Event;

This means that I can carry on using Laravel’s nice expressive syntax without worrying about naming collisions.