How to fetch/retrieve data from database in Laravel 8

How to fetch/retrieve data from database in Laravel 8

In this post, you will learn how to fetch / retrieve data from database in laravel where we will be using Bootstrap 5 version to design the user interface which is to design the HTML table to display the data from database using eloquent model in laravel.

So before getting started, Create a new laravel project and give the Database Connection in .env file.

Step 1: To fetch the data from database you have been already created a Model and Migration and a Controller in laravel application: 

Step 2: Give a route to call the function in your controller for calling the page in the following path: routes/web.php as follows:


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

Route::get('students', [StudentController::class'index']);

Step 3: Let's go to the controller in the following path : app/Http/Controllers/StudentController.php file.


namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
    public function index()
        $student = Student::all();
        return view('student.index'compact('student'));

Step 4: Create a blade file named index.blade.php inside student folder as the following path: resources/views/student/index.blade.php file as follows:



<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>How to Fetch data in Laravel 8</h4>
                <div class="card-body">

                    <table class="table table-bordered table-striped">
                            @foreach ($student as $item)
                                <td>{{ $item->id }}</td>
                                <td>{{ $item->name }}</td>
                                <td>{{ $item->email }}</td>
                                <td>{{ $item->course }}</td>
                                <td>{{ $item->section }}</td>
                                    <a href="" class="btn btn-primary btn-sm">Edit</a>
                                    <a href="" class="btn btn-danger btn-sm">Delete</a>



Now, you can successfully run the application by the following command:

$ php artisan serve

now lets go to the browser at the link: http://localhost:8000/students

Thanks for reading...