What is a Laravel Model ?




LARAVEL MODELS

Just like any other programming language, models in Laravel helps to establish a data communication with the storage of the application (Local or Database).
A Model is used to query a Database and then return the results to a controller.

The above image shows a Laravel model that can be easily created using ARTISAN from the command line. You should have laravel installed before trying to use artisan.
From the command line, navigate into the project folder and then you can use artisan for makiing a model. For example php artisan make:model Test and that will create a model named Test which can be found insdie the App/ folder of your project. After creating the model "Test" it can communicate to a table called "tests" (plural of the model name). 

HOW TO MAKE TABLES

Generating a table is fairly simple in Laravel but for that, you need to setup your database first. If you are using phpmyadmin, then you need to first create a database and then set it up in the .env file of your project as below 


here, we created a new database named test-db and then connected it to our laravel project using the .env file inside our folder structure.
Now we need to create a table called tests inside this database, for that, we will use something called Laravel Migrations. To create a new migration, open command prompt and type php artisan make:migration create_tests_table and this will create a new migration for tests table inside database/migrations/ folder. 

You can now use the migration for creating the table inside your database by setting up the migration as required. An example is below 


The up() function runs when we run the migration which create a table named 'tests' with 4 columns. First will be the ID column which will be an AI unique column. Second will be a column that we create which is the name column that will be a string. The third and fourth columns are created by default in a laravel migration that are the created_at and updated_at columns.
The down() function runs when we rollback a migration. That simply deletes the table from the database.

With the migration set up, we can now use the command line to run the command php artisan migrate and this will create the new TESTS table in our database and now the TEST model can fetch data from the tests table whenever required. 


Comments

Popular posts from this blog

What is MVC Architecture ?

Getting started with Laravel | Laravel Part - I

What is Vue.js and how to get Started with it