Saturday, 16 July 2022

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5


In this tutorial, we are going to show you how to make CRUD Application Laravel 9 framework. We will explained you step by step, how can we perform CRUD Operation in Laravel 9 Framework. So if you beginner in Laravel framework then this tutorial will help you to build CRUD Application in Laravel 9 framework, and you will be able to create Laravel 9 CRUN Application. Here under this tutorial, we will use basic example to show you CRUD Operation in Laravel 9.

Recently Laravel has release Laravel 9 framework and in Laravel 9 framework there is several new features and LTS Support. Laravel 9 also introduced an Anonymous Sub Migration also and it also resolved migration class name Collison. One more things Laravel 9 framework has been use PHP 8 version and it has been support PHP string function, which are very useful for string operations. There are many new query builder function has been introduced under Laravel 9 framework which will more convenient when you have work with database operation. So you are learn Laravel framework first time then this tutorial will help you to create CRUD (Create, Read, Update and Delete) Operation in Laravel 9 framework.

In this tutorial, we will create Student CRUD Application in Laravel 9 framework. Under this CRUD Application we will make Application, in which we can Add new Student Data, with student image upload, edit or change existing student data, with form data validation, show single student data on the web page, delete or remove student data from data and fetch all student data from MySQL database and display on the web page in HTML table format with dynamic pagination link. We will also create table in MySQL database from this Laravel 9 application using Laravel 9 Migration, and after this, we will create Controller, Models and views file for student crud application. Under this Laravel 9 crud application we will use Bootstrap 5 library for design web page. You have to following below steps to create CRUD Application in Laravel 9 framework.


Step 1 - Download & Install 9


In the First Steps of Laravel 9 CRUD Application, we have to download and install fresh Laravel 9 Application in our computer. So for this, you have to goes to command prompt and then after goes into directory where you have run PHP 8 script and then after you have to run following command.


composer create-project --prefer-dist laravel/laravel laravel_9_crud


Once we have run this command then it will create laravel_9_crud directory and under this directory it will download and install Laravel 9 Application.

Step 2 - Make Database Connection


After install Laravel 9 application, first we need to create database connection with MySQL database. So for this we have to open .env file and under this file, we need to add MySQL database configuration like MySQL database name, MySQL database user namd and password details. Once we have define this details, then it will make MySQL database connection in Laravel 9 framework. Below you can find MySQL database configuration details.

.env

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


Step 3 - Create MySQL Table using Laravel 9 Migration


Under this step, we have to crate students table under MySQL database from this Laravel 9 Application using Migrations. So first we have to create migration file under Laravel 9 application, so we have to run following command in command prompt.


php artisan make:migration create_students_table --create=students


After run above command then you will find one new file under database/migrations directory. So for we have to open that file and under that file, we have to define following code under that migrations file for create students table in MySQL database.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('student_name');
            $table->string('student_email');
            $table->enum('student_gender', ['Male', 'Female']);
            $table->string('student_image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};



After above code in migration file, now for create table in MySQL database from this Laravel 9 application, so for this, we have to run following command in command prompt and it will migrate MySQL table defination to MySQL database and create students table in MySQL database from this Laravel 9 Application.


php artisan migrate





Step 4 - Create CRUD Model and Controller


Under this step, we have to create Controller and Models file for CRUD Operation. So for this, we have goes to command prompt and run following command, which will create new CRUD StudentController and Student Model class file under Laravel 9 framework.


php artisan make:controller StudentController --resource --model=Student


So after run above command it will create Student.php model class file under app/Models directory and we have to open that file and put following code under that file.

app/Models/Student.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    protected $fillable = ['student_name', 'student_email', 'student_gender', 'student_image'];
}



And after run above command it will also create CRUD Controller with name StudentController.php file under app/Http/Controllers directory.

So this StudentController.php file has been created with seven method by default which you can seen below.

  1. index() - This is root method of this Controller class.
  2. create() - This is method has been used for load Add student form in the browser.
  3. store() - This method has been used for handle Add student data request.
  4. show() - This method has been used for display single student data on the web page.
  5. edit() - This method has been used for load edit student form in the browser.
  6. update() - This method has been receive student update form data request.
  7. destroy() - This method has been used for delete student data from database.

For create CRUD Application, you have to put folliowing code under StudentController.php file.

app/Http/Controllers/StudentController.php app/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Student::latest()->paginate(5);

        return view('index', compact('data'))->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'student_name'          =>  'required',
            'student_email'         =>  'required|email|unique:students',
            'student_image'         =>  'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $file_name = time() . '.' . request()->student_image->getClientOriginalExtension();

        request()->student_image->move(public_path('images'), $file_name);

        $student = new Student;

        $student->student_name = $request->student_name;
        $student->student_email = $request->student_email;
        $student->student_gender = $request->student_gender;
        $student->student_image = $file_name;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        return view('show', compact('student'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit(Student $student)
    {
        return view('edit', compact('student'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Student $student)
    {
        $request->validate([
            'student_name'      =>  'required',
            'student_email'     =>  'required|email',
            'student_image'     =>  'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $student_image = $request->hidden_student_image;

        if($request->student_image != '')
        {
            $student_image = time() . '.' . request()->student_image->getClientOriginalExtension();

            request()->student_image->move(public_path('images'), $student_image);
        }

        $student = Student::find($request->hidden_id);

        $student->student_name = $request->student_name;

        $student->student_email = $request->student_email;

        $student->student_gender = $request->student_gender;

        $student->student_image = $student_image;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Data has been updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy(Student $student)
    {
        $student->delete();

        return redirect()->route('students.index')->with('success', 'Student Data deleted successfully');
    }
}



Step 5 - Add Service Provider for Bootstrap Pagination


In Laravel 9 framework produce default style pagination link which will not properly display if you have Bootstrap library. So for this, we have to open app/Providers/AppServiceProvider.php and under this file, we have to add Paginator::useBootstrap() code under boot() method for support the bootstrap pagination.

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}



So after adding this code, you Laravel 9 application will display proper pagination link on the web page.

Step 6 - Create Views Blades File


Under this steps, we have to create blades files for display HTML output in the browser. In the Laravel 9 framework, blades files has been stored under resources/views directory. Under this Laravel 9 CRUD Application, we have to create following views blades files.

  1. master.blade.php - This is master template file.
  2. index.blade.php - This file we will used for display MySQL table data on the web page in HTML table format with pagination link.
  3. create.blade.php - This file has been used for load Create Student form on the web page.
  4. show.blade.php - This file has been used for display single student data on the web page.
  5. edit.blade.php - This file has been used for load student edit form in the browser.

Below you can find source code of all blade file.

resources/views/master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 CRUD Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        
        <h1 class="text-primary mt-3 mb-4 text-center"><b>Laravel 9 Crud Application</b></h1>
        
        @yield('content')
        
    </div>
    
</body>
</html>


resources/views/index.blade.php

@extends('master')

@section('content')

@if($message = Session::get('success'))

<div class="alert alert-success">
	{{ $message }}
</div>

@endif

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Data</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.create') }}" class="btn btn-success btn-sm float-end">Add</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<table class="table table-bordered">
			<tr>
				<th>Image</th>
				<th>Name</th>
				<th>Email</th>
				<th>Gender</th>
				<th>Action</th>
			</tr>
			@if(count($data) > 0)

				@foreach($data as $row)

					<tr>
						<td><img src="{{ asset('images/' . $row->student_image) }}" width="75" /></td>
						<td>{{ $row->student_name }}</td>
						<td>{{ $row->student_email }}</td>
						<td>{{ $row->student_gender }}</td>
						<td>
							<form method="post" action="{{ route('students.destroy', $row->id) }}">
								@csrf
								@method('DELETE')
								<a href="{{ route('students.show', $row->id) }}" class="btn btn-primary btn-sm">View</a>
								<a href="{{ route('students.edit', $row->id) }}" class="btn btn-warning btn-sm">Edit</a>
								<input type="submit" class="btn btn-danger btn-sm" value="Delete" />
							</form>
							
						</td>
					</tr>

				@endforeach

			@else
				<tr>
					<td colspan="5" class="text-center">No Data Found</td>
				</tr>
			@endif
		</table>
		{!! $data->links() !!}
	</div>
</div>

@endsection


resources/views/create.blade.php

@extends('master')

@section('content')

@if($errors->any())

<div class="alert alert-danger">
	<ul>
	@foreach($errors->all() as $error)

		<li>{{ $error }}</li>

	@endforeach
	</ul>
</div>

@endif

<div class="card">
	<div class="card-header">Add Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.store') }}" enctype="multipart/form-data">
			@csrf
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
				</div>
			</div>
			<div class="text-center">
				<input type="submit" class="btn btn-primary" value="Add" />
			</div>	
		</form>
	</div>
</div>

@endsection('content')


resources/views/show.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Details</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.index') }}" class="btn btn-primary btn-sm float-end">View All</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Name</b></label>
			<div class="col-sm-10">
				{{ $student->student_name }}
			</div>
		</div>
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Email</b></label>
			<div class="col-sm-10">
				{{ $student->student_email }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Gender</b></label>
			<div class="col-sm-10">
				{{ $student->student_gender }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Image</b></label>
			<div class="col-sm-10">
				<img src="{{ asset('images/' .  $student->student_image) }}" width="200" class="img-thumbnail" />
			</div>
		</div>
	</div>
</div>

@endsection('content')


resources/views/edit.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">Edit Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.update', $student->id) }}" enctype="multipart/form-data">
			@csrf
			@method('PUT')
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" value="{{ $student->student_name }}" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" value="{{ $student->student_email }}" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
					<br />
					<img src="{{ asset('images/' . $student->student_image) }}" width="100" class="img-thumbnail" />
					<input type="hidden" name="hidden_student_image" value="{{ $student->student_image }}" />
				</div>
			</div>
			<div class="text-center">
				<input type="hidden" name="hidden_id" value="{{ $student->id }}" />
				<input type="submit" class="btn btn-primary" value="Edit" />
			</div>	
		</form>
	</div>
</div>
<script>
document.getElementsByName('student_gender')[0].value = "{{ $student->student_gender }}";
</script>

@endsection('content')


Step 7 - Set Resource Route


Under this step, we have to add resource route for student crud application. So for set route, we have to open routes/web.php file and under this file, we have to define resource route for Laravel 9 CRUD Application.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});


Route::resource('students', StudentController::class);


After adding above code, then it will set route for all method of StudentController.php file.

Step 8 - Run Laravel 9 CRUD Application


When we have follow all above steps, that means our Laravel 9 CRUD Application is ready for check output in the browser. So for check output in the browser, first we need to start Laravel 9 Application server, so for this, we have go to command prompt and run following command.


php artisan serve


So this command will start Laravel server and provide us base url of our Laravel 9 CRUD Application. So we have goes to browser, and type give below URL and view output of Laravel 9 CRUD Application.


http://127.0.0.1:8000/students


So this is complete step by step tutorial on Laravel 9 CRUD Application, so you have follow all above steps then you can able to learn How to perform Insert, Update, Delete and Read MySQL Data Operation in Laravel 9 framework and build CRUD Application Laravel 9 framework with MySQL database and Bootstrap 5 Library.

Laravel 9 CRUD Application Video Tutorial


1 - Load MySQL Data in HTML Table with Pagination Links



2 - Insert or Add Data into MySQL Table



3 - Retrieve MySQL Data & Display on Web page



4 - Update or Edit MySQL Data



5 - Delete or Remove Data From MySQL



0 comments:

Post a Comment