In the previous tutorial, we learnt how to insert data into the database using Larave l1.In this tutorial, we will learn How to fetch/read data from MySQL database using Laravel 11.
Minimum requirement: PHP 8.2 or higher is needed to run Laravel 11.
We already created a MySQL table in the previous tutorial. Table structure for table tblusers
.
CREATE TABLE `tblusers` ( `id` int(11) NOT NULL, `firstName` varchar(255) DEFAULT NULL, `lastName` varchar(255) DEFAULT NULL, `emailId` varchar(255) DEFAULT NULL, `mobileNumber` bigint(11) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, `state` varchar(255) DEFAULT NULL, `city` varchar(255) DEFAULT NULL, `postingDate` timestamp NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Step 1: Create a controller for data fetching.
php artisan make:controller fetchController
Add logic to fetch/read data in the controller (app/Http/Controllers/fetchController.php)
<?php namespace AppHttpControllers; use IlluminateSupportFacadesDB; use IlluminateHttpRequest; class fetchController extends Controller { public function showData(){ $users=DB::table('tblusers') ->get(); return view('fetch',['data' => $users]); } }
Step 2: Create a blade template to display/show data.
<table class="table table-striped table-hover table-bordered"> <thead> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Email id</th> <th>Mobile No</th> <th>Address</th> <th>City</th> <th>State</th> </tr> </thead> <tbody> @foreach ($data as $id => $user ) <tr> <td>1</td> <td>{{ $user->firstName }}</td> <td>{{ $user->lastName }}</td> <td>{{ $user->emailId }}</td> <td>{{ $user->mobileNumber }}</td> <td>{{ $user->address }}</td> <td>{{ $user->city }}</td> <td>{{ $user->state }}</td> </tr> @endforeach </tbody> </table>
Step 3: Add the routes to the routes/web.php
<?php use IlluminateSupportFacadesRoute; use AppHttpControllersinsertController; use AppHttpControllersfetchController; // For Form View Route::get('/', function () { return view('form'); })->name('form'); // For Insert Data Route::post('/insertdata',[insertController::class,'insertdata'])->name('insertdata'); //For Fetch/Read Data Route::get('/fetch',[fetchController::class,'showData'])->name('fetch');
How to run the Script
1. Download the project zip file
2. Extract the file and copy insert-app
folder
3. Paste inside root directory (for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/Html)
4.Open PHPMyAdmin (http://localhost/phpmyadmin)
5. Create a database with the name userdb
6. Import userdb.sql
file(given inside the zip package in SQL file folder)
7. Run these command
PS C :> cd xampp/htdocs/insert-app
PS C:xampphtdocsinsert-app> php artisan serve
8. After that open the browser run the script
The post How to fetch / read data into MySQL database using Laravel 11 appeared first on PHPGurukul.
Source: Read MoreÂ