How To Display Data In Html Table In Laravel 8 ?

How To Display Data In Html Table In Laravel 8

In previous tutorial we have learn how to use get method in laravel. And today in this tutorial you learn How To Display Data In Html Table using model In Laravel . The get method is use in route and display data in html table.

Following are the few simple step in Laravel how to fetch data from database.

In Laravel get data from database in controller you need to create view ,model and controller. This script is possible laravel model view controller.

I create db in mysql with the name of test and one table with the name of users.

Step 01: Create User table in test database

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `email`, `password`) VALUES
(24, 'admin3', 'shrafathussain786@gmail.com', '5656'),
(25, 'sadaqat ali', 'admin@gmail.com', '6776'),
(26, 'pao', 'johnDoe@gmail.com', '767');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD UNIQUE KEY `id` (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
COMMIT;

Step 02: Find .env file in your laravel project and add the database credential.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 03: Open resource folder create userlsit in view directory.

<h1 style="text-align: center;">User List</h1>
<table border="1" width="100%">
	<THEAD>
	<th>ID</th>
	<th>NAME</th>
	<th>EMAIL</th>
	<th>PHOTO</th>
</THEAD>
<TR>
	@foreach ($collection as $userlst)
	<TD>{{$userlst['id']}}</TD>
	<TD>{{$userlst['first_name']}}</TD>
	<TD>{{$userlst['email']}}</TD>
	<TD style= "text-align: center;"><img src="{{$userlst['avatar']}}"></TD>
</TR>
@endforeach
</table>

Step 04: Go to the route folder and open web.php and create route for userlsit.blade.php

Route::post("user",[UserController::class, 'getDate']);

Step 05: Open your terminal and make user model for user table.

php artisan make:model usermodel

Step 06: Open your terminal and make UserController for create function to get the table from database.

php artisan make:controller UserController

Step 07: Use the user model in UserController

use App\Models\User;

Step 08: Add the following function function in UserController.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Course;
class CourseController extends Controller
{
    //
    function show(){
    	//return DB::select("select * From users");
    	$data=User::all();
    	return view('userlist',['user'=>$data]);

    }

}

Leave a Reply