Laravel Crud Operation - Insert Data

Laravel Crud Operation - Insert Data

In this article, I will inform you how to insert the data into the database in the "Laravel Crud Operation". This article is the first part of the "Laravel crud operation". In this article, I will inform you about the process of adding a new record to your database with ease. If you're a beginner, this article is very helpful. Don't miss this opportunity to enhance your Laravel skills and improve your web application development efficiency.

Requirement of Crud Operation

  1. Composer
  2. XAMPP or WAMP
  3. Browsers like Chrome, Edge, Firefox Etc
  4. IDE like VS Code, Sublime, Atom, etc
Get Source Code

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.

Laravel Crud Operation

Create View files

In this step, we are creating the 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>


This HTML code represents the layout template of a web page in a Laravel application. It serves as a blueprint for rendering pages with consistent styling and structure. Here's a breakdown of the key components:
  1. Document Type Declaration (<!DOCTYPE html>): Specifies that the document is an HTML5 document, ensuring compatibility with modern web browsers.
  2. 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.
  3. Metadata:
    1. Charset and viewport meta tags ensure proper character encoding and responsive layout on various devices.
    2. The X-UA-Compatible meta tag specifies the version of Internet Explorer compatibility mode to use.
    3. The <title> tag sets the title of the page displayed in the browser tab to "Crud - Laravel".
  4. External Resources:
    1. 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.
    2. Custom CSS: The style.css file, located in the crud_asset/css directory, is linked to provide additional custom styling for the web page.
  5. 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.
  6. JavaScript Libraries:
    1. Bootstrap JavaScript: The Bootstrap JavaScript library, also loaded via a CDN link, enables interactive components and functionalities provided by Bootstrap.
    2. jQuery: The jQuery library, included from a CDN link, is a popular JavaScript library that simplifies DOM manipulation and event-handling tasks.
    3. Custom JavaScript: The style.js file, located in the crud_asset/js directory, is linked to provide custom JavaScript functionality for the web page.
This layout template establishes the basic structure, styling, and interactivity for web pages in the Laravel application. It incorporates external resources such as Bootstrap CSS and JavaScript, along with custom CSS and JavaScript files, to create visually appealing and functional user interfaces. Additionally, it includes placeholders for dynamic content injection, ensuring consistency and ease of development across multiple pages.

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

The provided code represents a Laravel view file, likely named create.blade.php, which is a part of a CRUD (Create, Read, Update, Delete) application. Its purpose is to display a form for users to input data. Let's dissect it:

Layout Extension: The view extends a layout file named crud.layout. This is a common practice in Laravel to maintain consistency across multiple views by inheriting common elements from a layout file.

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.

Form Structure: Inside the content section, a standard HTML form is set up. The form's action attribute points to the route named 'submit.form', indicating where the form data will be submitted upon completion. The method attribute is set to post, specifying that the form data will be sent using the HTTP POST method. Additionally, @csrf generates a CSRF token field to protect against CSRF attacks, ensuring the security of the form submission.

Form Fields: The form contains various input fields to collect user information such as name, email, contact number, profile picture, password, and confirm password. Each input field is enclosed within an element styled using Bootstrap classes to structure them into rows and columns for a visually appealing layout.

Validation Errors Handling: Below each input field, there's a mechanism to display validation errors. Laravel's @error directive is used to check for errors associated with each input field. If validation fails (e.g., required field missing, invalid email format), the corresponding error message will be displayed using Bootstrap alert styling, providing feedback to the user on how to correct the input.

Submit Button: Lastly, the form includes a submit button labeled "SUBMIT". When clicked, this button triggers the submission of the form data to the server for processing.

This Laravel view file creates a structured and visually appealing form interface for users to input data, complete with built-in error handling to ensure data integrity and provide user feedback during the submission process.

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');
    }
};

The provided PHP code snippet is a Laravel migration file, a component used to manage changes to the database schema. In Laravel, migrations are used to create and modify database tables in a consistent and version-controlled manner. 

This particular migration file defines an anonymous class that extends the `Migration` class provided by Laravel. Within this class, two methods are defined: `up()` and `down()`. 

In the `up()` method, which is executed when the migration is run, a database table named `'crud_table'` is created using the `Schema::create()` method provided by Laravel's database schema builder. This table is structured with several columns to store user data such as name, email, contact information, profile picture filename, and password. Additionally, the `timestamps()` method is called to automatically add `created_at` and `updated_at` columns to track the creation and last update timestamps of records in the table.

Conversely, the `down()` method specifies the reverse of the `up()` operation. In this case, it drops the `'crud_table'` table if it exists, ensuring that the migration can be rolled back, effectively undoing the changes made to the database schema.

Overall, this migration file encapsulates the logic necessary to create a database table for a CRUD application, ensuring that database schema changes can be easily managed, tracked, and rolled back as needed during the application's lifecycle.

Model File Code

<?php
namespace App\Models\crud;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CrudModel extends Model
{
    use HasFactory;
    protected $table = 'crud_table';
    protected $fillable = ['name','email','contact','profile','password'];
}

This PHP code snippet represents a Laravel Eloquent model named CrudModel, typically stored in a file named CrudModel.php within the App\Models\crud namespace. Laravel's Eloquent ORM (Object-Relational Mapping) provides a convenient way to interact with database tables using PHP objects.

Let's break down the code:

Namespace: The namespace App\Models\crud; statement defines the namespace in which this model resides. Namespaces help organize code and prevent naming conflicts.

Model Class Definition: The CrudModel class extends Laravel's Model class, inheriting various functionalities provided by Eloquent.

Traits: The use HasFactory; statement indicates that the model utilizes the HasFactory trait. This trait provides a factory builder for generating model instances, aiding in database seeding and testing.

Table Name: The $table property is set to 'crud_table', specifying the name of the database table associated with this model. In this case, it indicates that instances of CrudModel correspond to records in the 'crud_table' table.

Fillable Attributes: The $fillable property is an array containing the names of attributes that are mass-assignable. Mass assignment allows you to set multiple attributes of the model using a single array, which is particularly useful when dealing with form submissions or API requests. In this case, attributes such as 'name', 'email', 'contact', 'profile', and 'password' can be mass assigned.

Overall, this model class serves as an intermediary between the Laravel application and the database table 'crud_table', providing methods and properties for interacting with and manipulating records in the table. It encapsulates database-related logic and facilitates tasks such as data retrieval, insertion, updating, and deletion within the CRUD application.

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');
        }
    }
}

This PHP code represents a Laravel controller class named CrudController located within the App\Http\Controllers\Crud namespace. In Laravel, controllers handle incoming HTTP requests and execute application logic, typically interacting with models and returning responses.


1. Namespace and Imports: The controller is defined within the App\Http\Controllers\Crud namespace. It imports several classes necessary for its functionality, including Controller (the base controller class provided by Laravel), Request (for handling HTTP requests), CrudModel (the Eloquent model representing the CRUD data), and Hash (for securely hashing passwords).

2. Class Definition: The CrudController class extends the base Laravel Controller class, inheriting its methods and functionality.

3. index() Method: This method handles the HTTP GET request to display the form for creating new CRUD records. It returns a view named crud.pages.form, typically containing the HTML form markup.

4. submit() Method: This method handles the HTTP POST request to submit data from the form. It first validates the incoming request data using Laravel's validation system, specifying rules for each form field such as required fields, minimum length, email format, uniqueness, numeric format, and file MIME type. If validation fails, it redirects back to the form page with validation error messages. If validation passes, it proceeds to process the form data:

  1. It renames the uploaded profile image file to include the user's username and a timestamp to prevent naming conflicts.
  2. It moves the uploaded image file to a designated folder within the public directory.
  3. 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.
  4. It saves the new record to the database using Eloquent's save() method.
  5. 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.
This controller manages the process of displaying the form for creating new CRUD records and handling the submission of form data, ensuring validation, data processing, and proper redirection with appropriate messages.

Post a Comment

Previous Post Next Post

Recent in Technology