How to create a model in Laravel - Tutorial
In this tutorial, we'll look at the right way to create a new model in Laravel - one of the most popular, robust and easy-to-use PHP framework. Laravel is an MVC (Model - View - Controller) framework, which means 'Models' are going to be at the core of any application that we develop.
In order to interact with the database using Models, Laravel provides Eloquent - an Object-Relational Mapping implementation of the Active Record. Eloquent makes it super easy to interact with our database and perform most common database operations.
I'll assume that you have already installed Laravel on your development machine and are now looking to create your first model. You should now make sure that you are able to connect to the database and have proper configuration in place in your .env file.
Create a Model with Artisan
While you can hand-code your model from scratch, there's an easy and officially recommended way to generate model with just one command.
php artisan make:model Post
You'll have to execute that command in your project's root. Once the command is run, Laravel will create following file (model) -
Of course you can arrange all your models inside a folder. You will simply have to tweak your make:model command as follows -
php artisan make:model Models/Blog/Post
This namespacing will create your model file inside -
Of course, Laravel will automatically take care of adding proper namespaces and classes in the file. Your model class will extend Laravel's 'Model' class.
Bonus Tip: Create Model with Database migration
If you wish to create migration along with your Model file automatically, Laravel provides an easy way to do that. Simply modify your artisan command as follows -
php artisan make:model Models/Blog/Post -m
That -m at the end of artisan command will automatically generate a related migration file in your /database/migrations/ folder.
Laravel Provides User Model By Default
Lot of newbie Laravel developers run into one of the most common issue; and 99% of them are trying to create the 'User' model. You don't have to create user model because it's provided by Laravel by default.
I hope this helps you get started with Laravel. If you have questions about Laravel, ask them below or simply join our Laravel Developers Group on CrazyEngineers.