Laravel Fetch (Retrive) Records from Database Example Tutorial

Laravel fetch data from database example tutorial; In this tutorial you will learn how to retrieve records from database in Laravel application. Fetching single or multiple records from database in laravel is very easy. You can get all records or single record using model or db table from your controller and display the list in blade view file

.Here we are using students to show in blade file model base. Let’s checkout the code according your requirement of mode you just need to change which data your want to fetch.

Add Route

You routes have something like where you have added one route for fetchin/retriving the data from database in laravel application.

routes\web.php

<?php

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

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

Controller Code

Here we are getting the students records from database so we are using Student model here, You can use the DB::table also.

app\Http\Controllers\StudentController.php

<?php

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
    public function index(Request $request)
    {
        $students = Student::get(); // get data using model

        return view('students', compact('students'));
    }
}

Blade File Code

For showing the records in blade view file we need to add the blade file and run the records using foreach loop just like below.

resources\views\students.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Retrive Data from Database</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"/>
</head>
<body>

<div class="container mt-5">
    <h2 class="mb-4">Laravel Fetch Data from Database</h2>
    <table class="table table-bordered">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Full Name</th>
            <th width="280px">Actions</th>
        </tr>
        @foreach ($students as $student)
            <tr>
                <td>{{ $student->name }}</td>
                <td>{{ $student->email }}</td>
                <td>{{ $student->phone }}</td>
                <td>{{ $student->dob     }}</td>
                <td>
                    <button class="btn btn-primary">Edit</button>
                    <button class="btn btn-danger" onclick="deleteConfirmation({{$student->id}})">Delete</button>
                </td>
            </tr>
        @endforeach
    </table>
</div>

</body>
</html>

I hope this example help you.

Leave a Comment