4

I know it's not possible to use a reserved word in PHP as class name, but my Laravel app enables managing of courses and classes, so I have a database table called classes, a ClassController and hopefully a Class model. However, in Laravel, my model has to be named Class which is not allowed in PHP:

class Class extends Model {}

Using a synonym, the closest being Lecture, still doesn't seem right.

Is there a Laravel workaround to this?

Community
  • 1
  • 1
Obay
  • 3,135
  • 15
  • 55
  • 78
  • 4
    `in Laravel, my model has to be named Class` you can name the model whatever you want, call it ClassModel? – samrap Oct 14 '15 at 15:28

1 Answers1

6

Laravel doesn't force you to use specific names for your models or controllers. It's just a convention. You can name your model whatever you want it to be. the only amend you will have to make is to declare protected $table = 'classes' in your model

Almazik G
  • 1,066
  • 1
  • 9
  • 21
  • Super cool this helped me a lot. Is this the only puprose of declaring `protected $table` in model? When we want to use a reserved word? Do you know where I can find a list of reserved words for laravel? Apparently `Entity` was one. – Noitidart Nov 01 '17 at 00:24
  • 1
    @Noitidart the purpose of having `protected $table` declared is to override naming convention that Laravel follows. Laravel will assume that your table name is pluralized version of your model name, i.e. you may have model called `Video`, then it's going to look for table `videos`. but if you want to name your model `VideoModel` it's going to look for `video_models` table. this is where you define -- nope, it's still just `protected $table = 'videos';` – Almazik G Nov 03 '17 at 13:05
  • I'm pretty sure you can have model named `Entity` tho. the only restrictions are the PHP reserved words http://php.net/manual/en/reserved.php – Almazik G Nov 03 '17 at 13:06
  • Thanks @Almazik for a detailed description for a new comer like me this is invaluble! I kept having problems with an Entity model because it was looking for plural of "entities" rather then "entitys" ("ies" vs "ys"). – Noitidart Nov 03 '17 at 15:36
  • 1
    @Noitidart exactly, it's smart to know that this is `ies` in this case. so again, `protected $table` to the rescue – Almazik G Nov 04 '17 at 16:48
  • That is so cool, I learned that the hard way haha. Is there a rulebook for this in the docs somewhere? Or is it just all words ending in `y` get `ies`? – Noitidart Nov 04 '17 at 20:53
  • I'm not sure about the rule book, I guess that's just general english language rules – Almazik G Nov 05 '17 at 08:18