What is a Laravel Model

What is a Laravel Model

Laravel Model is a class that describes the logical structure and relationship of the data. The model maintains fundamental behaviours and data of the application. Each of the DB tables has its own “Model” that allows user to interact with that DB tables. Models provide us the functionality to insert, retrieve and update information into your data table. 

Creating a Model

You can easily create a model with the help of artisan commands as following 

  • Open Command Prompt.
  • Navigate to your project directory.
  • Execute php artisan make:model Page. Here, I created the Page model.
  • This will create a replacement file Page.php in app/ directory.

Load DB Class and create method –

  • Search for Page.php file
  • Import DB class using (use DB).
  • Create single static method getuserData().
  • Fetch all records from the users table using DB::table(‘users’)->orderBy(‘id’,’asc’)->get().
  • Return $value.

NOTE – To use DB for database manipulation got to import DB class with use DB.

Complete Code is as follow

<?php

namespace App;

use DB;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {

  public static function getuserData(){

    $value=DB::table(‘users’)->orderBy(‘id’, ‘asc’)->get();

    return $value;

  }

}

Conclusion

PHP is a powerful language. Laravel is taken into account a famous and robust PHP framework. It provides an efficient way of tracking SQL queries.  You can find all models is stored in the main app directory in the root of the project.

Final Words

I hope this article helps you know better about Laravel Mo. If it is useful for you in any manner, then do share it on social media, stay connected with me for the new update & contact me for any inquiry.

Posted in LaravelTags:

Write a comment