Laravel Crud Operation - Fetch and Display the Data

Laravel Crud Operation - Fetch and Display the Data

In this article, we learn about the process of fetching data and displaying the data in the "Laravel crud operation". This is the second article on the "Laravel crud operation".

Laravel Crud Operation

In the first article, I have already explained the requirement file, software, and basic layout. So let's start the code for displaying the records.

Create the route


Route::get('/crud/data', [CrudController::class, 'showdata'])->name('view.data');

This Laravel route definition is using the Route::get() method to handle HTTP GET requests to the /crud/data URL path. When a user navigates to this URL in their browser, the specified controller action will be invoked.

1. HTTP Method: Route::get() indicates that this route is triggered by HTTP GET requests. In other words, it's expecting a user to fetch data from the specified URL.

2. URL Path: /crud/data represents the specific URL path that triggers this route. When a user visits this path in their browser, the associated controller action will be executed.

3. Controller Action: [CrudController::class, 'showdata'] specifies the controller class and the method within that class that should be invoked when this route is triggered. In this case, it's calling the showdata() method of the CrudController class.

4. Route Name: ->name('view.data') assigns a name to this route, allowing developers to refer to it by name in other parts of the application. This is useful for generating URLs or redirects programmatically without hardcoding the URL path.

This route definition establishes a URL path /crud/data that, when accessed via HTTP GET request, invokes the showdata() method of the CrudController class. The route is named 'view.data', enabling easy reference and generation of URLs elsewhere in the Laravel application.


View file

Create the view file and write the table structure code.

show.blade.php(File Name)
@extends('crud.layout')
@section('content')
    <div class="container mt-5 p-0">
        <div class="row">
            <div class="col-lg-12">
                <div class="card align-middle">
                    <div class="card-header">
                        <div class="col-lg-6">
                            <h4>Crud Operation In Laravel - Crud Table</h4>
                        </div>
                        <div class="col-lg-6 aling">
                            <a class="add_link" href="{{route('form')}}">Add New</a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-dark table-striped table-bordered table-hover table-responsive table-lg-responsive align-middle">
                            <thead>
                                <tr>
                                    <th>S NO</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Contact</th>
                                    <th>Profile</th>
                                    <th>Update Password</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

The provided code is a Blade template file named show.blade.php, which likely represents a view for displaying data from a CRUD (Create, Read, Update, Delete) operation in a Laravel application. Let's analyze the code:

1. Layout Extension: The view extends a layout file named crud.layout, indicating that it inherits the structure and styling defined in that layout file.

2. Content Section: Within the layout, there's a defined section named 'content'. This section serves as a placeholder where the content specific to this view will be injected. In this case, it contains the HTML markup for displaying the data table.

3. Container and Row Structure: The content is enclosed within a Bootstrap container and row ( and ), which help to organize and align the content on the page.

4. Card Component: The main content is wrapped inside a Bootstrap card component (). This card displays a header and body section.

5. Header Section: The card header contains a title ("Crud Operation In Laravel - Crud Table") and a link labeled "Add New". The link uses Laravel's route() function to generate the URL for the route named 'form', which likely leads to a form for adding new data entries.

6. Table: The card body contains an empty table () with headings for various fields such as "S NO", "Name", "Email", "Contact", "Profile", "Update Password", and "Action". This table is where the data retrieved from the database will be displayed dynamically.

7. Table Body: The element is currently empty (), indicating that there are no rows of data to display yet. This section will be populated dynamically with data retrieved from the database using PHP or JavaScript.

This Blade template provides the structure and layout for displaying data in a tabular format. It includes placeholders for dynamic content injection and utilizes Bootstrap classes for styling and responsiveness, making it suitable for use in a Laravel application.

Laravel Crud Operation

Controller Code 

public function showdata()
{
    $cruddata = CrudModel::all();
    return view('crud.pages.show', compact('cruddata'));
}

The provided PHP code snippet is a method definition within a Laravel controller class, likely named CrudController. This method, named showdata(), is responsible for fetching data from the database and passing it to a view for display. Here's a breakdown of the code:

1. Method Definition: The showdata() method is declared as a public function within the controller class.

2. Data Retrieval: Inside the method, data is retrieved from the database using the "CrudModel::all()" method. This method retrieves all records from the CrudModel database table and assigns them to the variable "$cruddata".

3. View Rendering: The method then returns a view named 'crud.pages.show', passing the retrieved data to the view using the compact() function. The compact() function creates an associative array where the key is the variable name ('cruddata' in this case) and the value is the variable's value ($cruddata). This allows the data to be accessed within the view using the specified variable name.

4. View File: Presumably, there is a Blade template file named "show.blade.php" located in the crud/pages directory, which will receive the "$cruddata" variable passed from the controller. This view file will contain HTML markup and Blade directives to display the data retrieved from the database.

This method retrieves all records from the CrudModel database table, passes them to a view named 'crud.pages.show', and renders the view to display the data to the user. This approach follows the MVC (Model-View-Controller) pattern commonly used in Laravel applications, where the controller handles data retrieval and passes it to the view for presentation to the user.

View the file with the record

show.blade.php
@extends('crud.layout')
@section('content')
    <div class="container mt-5 p-0">
        <div class="row">
            <div class="col-lg-12">
                <div class="card align-middle">
                    <div class="card-header">
                        <div class="col-lg-6">
                            <h4>Crud Operation In Laravel - Crud Table</h4>
                        </div>
                        <div class="col-lg-6 aling">
                            <a class="add_link" href="{{route('form')}}">Add New</a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-dark table-striped table-bordered table-hover table-responsive table-lg-responsive align-middle">
                            @if (session('success'))
                                <div class="alert alert-success">
                                    {{ session('success') }}
                                </div>
                            @endif
                            @if (session('error'))
                                <div class="alert alert-danger">
                                    {{ session('error') }}
                                </div>
                            @endif
                            <thead>
                                <tr>
                                    <th>S NO</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Contact</th>
                                    <th>Profile</th>
                                    <th>Update Password</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $numver = 1;
                                @endphp
                                @foreach ($cruddata as  $keys => $cruddata_val)
                                    <tr>
                                        <td>{{$numver++}}</td>
                                        <td>{{$cruddata_val->name}}</td>
                                        <td>{{$cruddata_val->email}}</td>
                                        <td>{{$cruddata_val->contact}}</td>
                                        <td>
                                            <img class="img-fluid img-thumbnail"  src="{{asset('crud_asset/image/'). '/'. $cruddata_val->profile}}" style="width: 100px; height:50px">
                                        </td>
                                        <td><a href="{{route('passwordview.data', ['id' => $cruddata_val->id])}}" class="password_update_link">Update Password</a></td>
                                        <td>
                                            <a href="{{route('updateview.data', ['id' => $cruddata_val->id])}}" class="update_link">Update</a>
                                            <a href="{{route('delete.data', ['id' => $cruddata_val->id])}}" class="delete_link">Delete</a>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

This Blade template file, likely named show.blade.php, is responsible for rendering a view to display data retrieved from the database in a tabular format. 

Laravel Crud Operation


1. Layout Extension: The view extends a layout file named "crud.layout." This layout likely contains common elements such as header, navigation, and footer, providing a consistent structure and styling across multiple views.

2. Content Section: Within the layout, there's a defined section named 'content'. This section serves as a placeholder where the content specific to this view will be injected.

3. Container and Row Structure: The content is enclosed within a Bootstrap container and row ( and ). This structure helps to organize and align the content on the page.

4. Card Component: The main content is wrapped inside a Bootstrap card component (). This card contains a header section and a body section.

5. Header Section: The card header contains a title ("Crud Operation In Laravel - Crud Table") and a link labeled "Add New". The link uses Laravel's route() function to generate the URL for the route named 'form', presumably leading to a form for adding new data entries.

6. Flash Messages: Inside the table, there are sections to display flash messages (success or error messages) if they exist in the session. Flash messages are often used to provide feedback to users after certain actions such as record creation, update, or deletion.

7. Table: The card body contains a table () for displaying the data. It has columns for various fields such as "S NO", "Name", "Email", "Contact", "Profile", "Update Password", and "Action".

8. Table Body: The element contains a loop (@foreach) that iterates over the $cruddata collection passed from the controller. For each item in the collection, it generates a table row () and populates the columns with data from the corresponding model properties. Additionally, it includes links for updating passwords, updating records, and deleting records. These links use Laravel's route() function to generate URLs for specific routes, passing the relevant record ID as a parameter.

This Blade template provides a structured and visually appealing interface for viewing CRUD data, with features like flash messages for user feedback and dynamic generation of table rows based on data retrieved from the database.

Post a Comment

Previous Post Next Post

Recent in Technology