SlideShare a Scribd company logo
1 of 16
Download to read offline
How to Create and Load
Model in Laravel
By Makitweb
A model is a PHP class where perform data logic and database manipulation
like – retrieve data, insert, update, and delete.
In Laravel models classes are stored in app/ directory.
This mainly loads from the controller.
In this tutorial, I show how you create and load Model in the controller and fetch
records from MySQL database in Laravel.
Contents -
1. Table structure
2. Database Configuration
3. Model
4. Controller
5. Route
6. View
7. Conclusion
1. Table structure
I am using users table in the example.
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`name` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Database Configuration
Open .env file.
Specify the host, database name, username, and password.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=
3. Model
Create Model –
Open Command Prompt.
● Navigate to your project directory.
● Execute php artisan make:model Page. Here, I created Page model.
● This will create a new file Page.php in app/ directory.
Load DB Class and create method –
● Navigate to app/ directory and open Page.php.
● Import DB class 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 need to import DB class with use
DB;.
<?php
namespace App;
use DB;
use IlluminateDatabaseEloquentModel;
class Page extends Model {
public static function getuserData(){
$value=DB::table('users')->orderBy('id', 'asc')->get();
return $value;
}
}
4. Controller
Create Controller –
● Open Command Prompt.
● Navigate to project directory.
● Now, execute php artisan make::controller PagesController. Here, I
created PagesController.
Load Model –
● Navigate to app/Http/Controllers/ directory and open
PagesController.php.
● Import Page Model from App namespace with use AppPage outside of
class.
● Create an index() method where call getuserData() method of Page model
Page::getuserData() to fetch users data.
● Store in $userData variable and pass to index view.
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppPage;
class PagesController extends Controller{
public function index(){
// Read value from Model method
$userData = Page::getuserData();
// Pass to view
return view('index')->with("userData",$userData);
}
}
5. Route
Open web.php file in route/ directory.
Defined single route.
<?php
// Controller-name@method-name
Route::get('/', 'PagesController@index'); // localhost:8000/
6. View
Create a new file index.blade.php in resources/views/ directory.
Read values from $userData using @foreach and create new rows.
<!doctype html>
<html>
<body>
<table border='1' style='border-collapse: collapse;'>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($userData as $user)
<tr>
<td>{{ $user->username }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</body>
</html>
5. Conclusion
Before calling Model method from the controller first import Model class with
use. Similarly, for using DB in the model need to import DB class.
Share
For More Laravel related tutorial
as well as other programming tutorials visit :

More Related Content

What's hot

Organize directories for applications with front-end and back-end with yii - ...
Organize directories for applications with front-end and back-end with yii - ...Organize directories for applications with front-end and back-end with yii - ...
Organize directories for applications with front-end and back-end with yii - ...Framgia Vietnam
 
Ajax pagination using j query in rails3
Ajax pagination using j query in rails3Ajax pagination using j query in rails3
Ajax pagination using j query in rails3Andolasoft Inc
 
前后端mvc经验 - webrebuild 2011 session
前后端mvc经验 - webrebuild 2011 session前后端mvc经验 - webrebuild 2011 session
前后端mvc经验 - webrebuild 2011 sessionRANK LIU
 
Adrotator in asp
Adrotator in aspAdrotator in asp
Adrotator in aspSireesh K
 
The Chaos Tools Suite
The Chaos Tools SuiteThe Chaos Tools Suite
The Chaos Tools Suitemerlinofchaos
 
e computer notes - Other database objects
e computer notes - Other database objectse computer notes - Other database objects
e computer notes - Other database objectsecomputernotes
 
Leveraging the Chaos tool suite for module development
Leveraging the Chaos tool suite  for module developmentLeveraging the Chaos tool suite  for module development
Leveraging the Chaos tool suite for module developmentzroger
 
A Quick Introduction to YQL
A Quick Introduction to YQLA Quick Introduction to YQL
A Quick Introduction to YQLMax Manders
 
Integrate with database by groovy
Integrate with database by groovyIntegrate with database by groovy
Integrate with database by groovySon Nguyen
 
Mule with jdbc(my sql)
Mule with jdbc(my sql)Mule with jdbc(my sql)
Mule with jdbc(my sql)charan teja R
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 

What's hot (20)

Organize directories for applications with front-end and back-end with yii - ...
Organize directories for applications with front-end and back-end with yii - ...Organize directories for applications with front-end and back-end with yii - ...
Organize directories for applications with front-end and back-end with yii - ...
 
Ajax pagination using j query in rails3
Ajax pagination using j query in rails3Ajax pagination using j query in rails3
Ajax pagination using j query in rails3
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
 
前后端mvc经验 - webrebuild 2011 session
前后端mvc经验 - webrebuild 2011 session前后端mvc经验 - webrebuild 2011 session
前后端mvc经验 - webrebuild 2011 session
 
Adrotator in asp
Adrotator in aspAdrotator in asp
Adrotator in asp
 
lab56_db
lab56_dblab56_db
lab56_db
 
The Chaos Tools Suite
The Chaos Tools SuiteThe Chaos Tools Suite
The Chaos Tools Suite
 
Jsp session 5
Jsp   session 5Jsp   session 5
Jsp session 5
 
e computer notes - Other database objects
e computer notes - Other database objectse computer notes - Other database objects
e computer notes - Other database objects
 
Leveraging the Chaos tool suite for module development
Leveraging the Chaos tool suite  for module developmentLeveraging the Chaos tool suite  for module development
Leveraging the Chaos tool suite for module development
 
A Quick Introduction to YQL
A Quick Introduction to YQLA Quick Introduction to YQL
A Quick Introduction to YQL
 
Integrate with database by groovy
Integrate with database by groovyIntegrate with database by groovy
Integrate with database by groovy
 
Using jersey exception mapper
Using jersey exception mapperUsing jersey exception mapper
Using jersey exception mapper
 
Oracle database
Oracle databaseOracle database
Oracle database
 
Mule with jdbc(my sql)
Mule with jdbc(my sql)Mule with jdbc(my sql)
Mule with jdbc(my sql)
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Jsp session 4
Jsp   session 4Jsp   session 4
Jsp session 4
 
Chap4 4 2
Chap4 4 2Chap4 4 2
Chap4 4 2
 
Jsp intro
Jsp introJsp intro
Jsp intro
 
Create Database
Create Database Create Database
Create Database
 

Similar to How to Create and Load Model in Laravel

Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleKaty Slemon
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentationToufiq Mahmud
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsMichael Miles
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS DrupalMumbai
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes ramakesavan
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLAkhil Mittal
 

Similar to How to Create and Load Model in Laravel (20)

Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentation
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback Commands
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
PHP MVC
PHP MVCPHP MVC
PHP MVC
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
 

More from Yogesh singh

How to create Custom Page Template in WordPress
How to create Custom Page Template in WordPressHow to create Custom Page Template in WordPress
How to create Custom Page Template in WordPressYogesh singh
 
Drag and drop file upload with Dropzone in CodeIgniter
Drag and drop file upload with Dropzone in CodeIgniterDrag and drop file upload with Dropzone in CodeIgniter
Drag and drop file upload with Dropzone in CodeIgniterYogesh singh
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHPYogesh singh
 
Copy text to clipboard using vue-clipboard2 - Vue.js
Copy text to clipboard using vue-clipboard2 - Vue.jsCopy text to clipboard using vue-clipboard2 - Vue.js
Copy text to clipboard using vue-clipboard2 - Vue.jsYogesh singh
 
Create custom 404 error page in CodeIgniter
Create custom 404 error page in CodeIgniterCreate custom 404 error page in CodeIgniter
Create custom 404 error page in CodeIgniterYogesh singh
 
How to Schedule Posts in Wordpress without Plugin
How to Schedule Posts in Wordpress without PluginHow to Schedule Posts in Wordpress without Plugin
How to Schedule Posts in Wordpress without PluginYogesh singh
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJSYogesh singh
 
How to verify a domain in MailChimp
How to verify a domain in MailChimpHow to verify a domain in MailChimp
How to verify a domain in MailChimpYogesh singh
 

More from Yogesh singh (8)

How to create Custom Page Template in WordPress
How to create Custom Page Template in WordPressHow to create Custom Page Template in WordPress
How to create Custom Page Template in WordPress
 
Drag and drop file upload with Dropzone in CodeIgniter
Drag and drop file upload with Dropzone in CodeIgniterDrag and drop file upload with Dropzone in CodeIgniter
Drag and drop file upload with Dropzone in CodeIgniter
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHP
 
Copy text to clipboard using vue-clipboard2 - Vue.js
Copy text to clipboard using vue-clipboard2 - Vue.jsCopy text to clipboard using vue-clipboard2 - Vue.js
Copy text to clipboard using vue-clipboard2 - Vue.js
 
Create custom 404 error page in CodeIgniter
Create custom 404 error page in CodeIgniterCreate custom 404 error page in CodeIgniter
Create custom 404 error page in CodeIgniter
 
How to Schedule Posts in Wordpress without Plugin
How to Schedule Posts in Wordpress without PluginHow to Schedule Posts in Wordpress without Plugin
How to Schedule Posts in Wordpress without Plugin
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJS
 
How to verify a domain in MailChimp
How to verify a domain in MailChimpHow to verify a domain in MailChimp
How to verify a domain in MailChimp
 

Recently uploaded

Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...DrVipulVKapoor
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressMaria Paula Aroca
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 

Recently uploaded (20)

Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian Congress
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 

How to Create and Load Model in Laravel

  • 1. How to Create and Load Model in Laravel By Makitweb
  • 2. A model is a PHP class where perform data logic and database manipulation like – retrieve data, insert, update, and delete. In Laravel models classes are stored in app/ directory. This mainly loads from the controller. In this tutorial, I show how you create and load Model in the controller and fetch records from MySQL database in Laravel.
  • 3. Contents - 1. Table structure 2. Database Configuration 3. Model 4. Controller 5. Route 6. View 7. Conclusion
  • 4. 1. Table structure I am using users table in the example. CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  • 5. 2. Database Configuration Open .env file. Specify the host, database name, username, and password. DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=tutorial DB_USERNAME=root DB_PASSWORD=
  • 6. 3. Model Create Model – Open Command Prompt. ● Navigate to your project directory. ● Execute php artisan make:model Page. Here, I created Page model. ● This will create a new file Page.php in app/ directory.
  • 7. Load DB Class and create method – ● Navigate to app/ directory and open Page.php. ● Import DB class 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 need to import DB class with use DB;.
  • 8. <?php namespace App; use DB; use IlluminateDatabaseEloquentModel; class Page extends Model { public static function getuserData(){ $value=DB::table('users')->orderBy('id', 'asc')->get(); return $value; } }
  • 9. 4. Controller Create Controller – ● Open Command Prompt. ● Navigate to project directory. ● Now, execute php artisan make::controller PagesController. Here, I created PagesController.
  • 10. Load Model – ● Navigate to app/Http/Controllers/ directory and open PagesController.php. ● Import Page Model from App namespace with use AppPage outside of class. ● Create an index() method where call getuserData() method of Page model Page::getuserData() to fetch users data. ● Store in $userData variable and pass to index view.
  • 11. <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppPage; class PagesController extends Controller{ public function index(){ // Read value from Model method $userData = Page::getuserData(); // Pass to view return view('index')->with("userData",$userData); } }
  • 12. 5. Route Open web.php file in route/ directory. Defined single route. <?php // Controller-name@method-name Route::get('/', 'PagesController@index'); // localhost:8000/
  • 13. 6. View Create a new file index.blade.php in resources/views/ directory. Read values from $userData using @foreach and create new rows.
  • 14. <!doctype html> <html> <body> <table border='1' style='border-collapse: collapse;'> <tr> <th>Username</th> <th>Name</th> <th>Email</th> </tr> @foreach($userData as $user) <tr> <td>{{ $user->username }}</td> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> </tr> @endforeach </table> </body> </html>
  • 15. 5. Conclusion Before calling Model method from the controller first import Model class with use. Similarly, for using DB in the model need to import DB class.
  • 16. Share For More Laravel related tutorial as well as other programming tutorials visit :