Requirement of Crud Operation
- Composer
- XAMPP or WAMP
- Browsers like Chrome, Edge, Firefox Etc
- IDE like VS Code, Sublime, Atom, etc
Install Laravel application
If all requirements exist, install the Laravel application with the help of the following command.
composer create-project laravel/laravel Laravel-crud
ENV configuration:
In this step, we change the database name in the ".ENV" file. when you open the ".ENV" file you will see that the default name of the database in the ".ENV" file is "Laravel". I have changed the database name "Laravel" from "laravel_crud_and_Authetication".
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_crud_and_Authetication
DB_USERNAME=root
DB_PASSWORD=
Create the required files:
After configuring the ".ENV" file we create the model or migration file and after create the controller file.
We can create the model and migration file with the help of the following command at the same time.
php artisan make:model CrudModel -m
Note: If you want to create the model or migration file one by one. So you can run these commands.
php artisan make:model ModelName
php artisan make:migration MigrationName
And in the last create the controller with the help of the following command.
php artisan make:controller crud/CrudController -r
Create the routes
Route::get('/', [CrudController::class, 'index'])->name('form');
Route::post('/submit_data', [CrudController::class, 'submit'])->name('submit.form');
The provided Laravel routes code sets up two distinct routes within the application. The first route, defined with a GET method, establishes an endpoint for the root URL ('/'). When a user navigates to the root URL of the application, this route triggers the index method within the CrudController class. Typically, this method is responsible for rendering a form or a page where users can interact with the application. Additionally, the ->name('form') function assigns a name to this route, allowing developers to refer to it by its name rather than hardcoding the URL. In this case, the assigned name is 'form', facilitating easier URL generation or redirection within the application.
The second route is set up with a POST method and corresponds to the URL '/submit_data'. This route handles data submissions from forms within the application. When a user submits data to the URL /submit_data using the HTTP POST method, this route executes the submit method within the CrudController class. Typically, this method processes the submitted data, performs any necessary validation, and interacts with the database to store the data or carry out other relevant actions. Similar to the first route, the ->name('submit.form') function assigns a name to this route, which can be utilized for URL generation or redirection purposes. In this case, the name 'submit.form' is assigned to facilitate easier referencing of this route throughout the application's codebase.
Create View files
Layout File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Crud - Laravel</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link rel="stylesheet" href="{{asset('crud_asset/css/style.css')}}">
</head>
<body>
@yield('content')
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="{{asset('crud_asset/js/style.js')}}"></script>
</body>
</html>
- Document Type Declaration (<!DOCTYPE html>): Specifies that the document is an HTML5 document, ensuring compatibility with modern web browsers.
- HTML Structure: The document follows the standard HTML structure with <html>, <head>, and <body> elements. This structure organizes the content and metadata of the page.
- Metadata:
- Charset and viewport meta tags ensure proper character encoding and responsive layout on various devices.
- The X-UA-Compatible meta tag specifies the version of Internet Explorer compatibility mode to use.
- The <title> tag sets the title of the page displayed in the browser tab to "Crud - Laravel".
- External Resources:
- Bootstrap CSS: The Bootstrap CSS framework is included via a CDN link. It provides pre-styled components and layout utilities for building responsive web interfaces.
- Custom CSS: The style.css file, located in the crud_asset/css directory, is linked to provide additional custom styling for the web page.
- Content Section (@yield('content')): This section serves as a placeholder where the content from child views will be injected. It allows for dynamic content to be inserted into the layout, enabling flexibility in page design.
- JavaScript Libraries:
- Bootstrap JavaScript: The Bootstrap JavaScript library, also loaded via a CDN link, enables interactive components and functionalities provided by Bootstrap.
- jQuery: The jQuery library, included from a CDN link, is a popular JavaScript library that simplifies DOM manipulation and event-handling tasks.
- Custom JavaScript: The style.js file, located in the crud_asset/js directory, is linked to provide custom JavaScript functionality for the web page.
Form File
@extends('crud.layout')
@section('content')
<div class="container mt-5 p-0">
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h4>Crud Operation In Laravel</h4>
</div>
<div class="card-body">
<form action="{{route('submit.form')}}" method="post" enctype="multipart/form-data" >
@csrf
{{-- row-1 --}}
<div class="row m-2">
<div class="col-lg-6">
<input type="text" name="username" class="form-control" autocomplete="off" placeholder="Enter Your Name" value="{{old('username')}}">
@error('username')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</div>
<div class="col-lg-6">
<input type="email" name="useremail" class="form-control" autocomplete="off" placeholder="Enter Your Email" value="{{old('useremail')}}">
@error('useremail')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</div>
</div>
{{-- row-2 --}}
<div class="row m-2">
<div class="col-lg-6">
<input type="text" name="usercontact" class="form-control" autocomplete="off" placeholder="Enter Contact Number" value="{{old('usercontact')}}">
@error('usercontact')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</div>
<div class="col-lg-6">
<input type="file" name="userprofile" class="form-control" autocomplete="off" value="{{old('userprofile')}}">
@error('userprofile')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</div>
</div>
{{-- row-3 --}}
<div class="row m-2">
<div class="col-lg-6">
<input type="password" name="userpassword" class="form-control" autocomplete="off" placeholder="Create Your Password" value="{{old('userpassword')}}">
@error('userpassword')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</div>
<div class="col-lg-6">
<input type="password" name="userconfirmpassword" class="form-control" autocomplete="off" placeholder="Confirm Your Password" value="{{old('userconfirmpassword')}}">
@error('userconfirmpassword')
<div class="alert alert-danger">{{$message}}</div>
@enderror
</div>
</div>
{{-- row-4 --}}
<div class="row m-2">
<div class="col-lg-6">
<button type="submit" class="submitbutton">SUBMIT</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Migration File Code
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('crud_table', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('contact');
$table->string('profile');
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('crud_table');
}
};
Model File Code
Controller File Code
<?php
namespace App\Http\Controllers\Crud;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\crud\CrudModel;
use Hash;
class CrudController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return view('crud.pages.form');
}
/**
* Show the form for creating a new resource.
*/
public function submit(request $request)
{
$request->validate([
'username' => 'required|alpha|min:3',
'useremail' => 'required|email|unique:crud_table,email',
'usercontact' => 'required|numeric|min:10',
'userpassword' => 'required|min:8',
'userconfirmpassword' => 'required|min:8|same:userpassword',
'userprofile' => 'required|mimes:jpg,png,webp,jpeg',
]);
$image_name = $request->file('userprofile');
$image_rename = $request->input('username'). '_' .time() . '.' .$image_name->getClientOriginalExtension();
$file_located = public_path('/crud_asset/image/');
$cruddata = new CrudModel;
$cruddata->name = $request->input('username');
$cruddata->email = $request->input('useremail');
$cruddata->contact = $request->input('usercontact');
$cruddata->profile = $image_rename;
$cruddata->password = Hash::make($request->input('userpassword'));
$cruddata->save();
if($cruddata)
{
$image_name->move($file_located,$image_rename);
return redirect()->route('view.data')->with('success', 'Record Successfully Added');
}
else
{
return redirect()->back()->with('error', 'Record Not Successfully Added');
}
}
}
- It renames the uploaded profile image file to include the user's username and a timestamp to prevent naming conflicts.
- It moves the uploaded image file to a designated folder within the public directory.
- It creates a new instance of the CrudModel and populates its attributes with the validated form data, including hashed password using Laravel's Hash::make() method.
- It saves the new record to the database using Eloquent's save() method.
- If the record is successfully saved, it redirects to a route named 'view.data' (presumably to view the newly added data) with a success message. Otherwise, it redirects back to the form page with an error message.