Quantcast
Channel: Frank Michel Media
Viewing all articles
Browse latest Browse all 11

How to use an Eloquent model name which is already used by Laravel as a class name

$
0
0

Let's say you have a "requests" model that you would like to use in your application. Therefore you have set up an eloquent model like this:

// app/models/Request.php

class Request extends Eloquent {

    public function user()
    {
       return $this->belongsTo('User');     
    }

}

Unfortunately the "Request" class already exists in Laravel. So when using this model like Request::find(1) we will get an error.

Namespaces to the rescue! So let's do some slight modifications to the Eloquent model:

// app/models/Request.php

namespace Models;

use Eloquent;


class Request extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}

Awesome. Now we can use our model like this:

Models\Request::find(1);

Okay, we need to prefix it with our namespace if we want to use both the Laravel Request class and our model at the same time. But it's much cleaner than coming up with some other name for our model that will constantly bug us because it doesn't have a meaningful identifier.

Don't forget to update related Eloquent models in order to use the namespaced model in relationships:

// app/models/User.php

class User extends Eloquent {

    public function requests()
   {
       return $this->hasMany('Models\Request');
   }

}

Don't forget to run composer dump-autoload in case you have renamed your model.

Source

http://stackoverflow.com/questions/16116378/how-do-i-namespace-a-model-in-laravel-so-as-not-to-clash-with-an-existing-class 


Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images