Laravel Crud Operation - Insert Data

Laravel Crud Operation - Insert Data

Today I am starting the series of Laravel Crud Operations. In this series, we will understand the process of saving (CREATE), displaying (READ), editing (UPDATE), and removing (DELETE) data using Laravel Eloquent ORM. But in this article, I will only tell you the process of saving (CREATE) your data.

Laravel crud operation

Software Requirements

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

Steps of Crud Operation

Create Project: In this step, the project is created with the help of Laravel commands.
ENV Configuration: In this step, the database connection is created by configuring the ENV file.
Create Files: In this step, some files are created such as migration files, model files, controller files, and view files. Some of these files are created with the help of commands and some are created manually.

Create Project

Create Project: In this step, we will first install Laravel globally using the "composer global require laravel/installer" command. Next, the project is created using the "laravel new laravel-project" command. This command will create a folder named "laravel-project" which contains the folders or files related to Laravel that are downloaded. You can give any name to your folder.


You can also create a Laravel project using this command "composer create-project laravel/laravel project-name". But this will not install Laravel globally.

                                 
  composer create-project laravel/laravel laravel-crud
                                   

Note: To create a project, you must install "Composer" first.

ENV Configuration

In this step, the ".ENV" file is configured by adding the database name or password or creating a connection with the database.


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


This code is part of a configuration file that configures the database connection in Laravel (PHP framework). Each line has its own specific meaning:
DB_CONNECTION=mysql: This means that your application will connect to the MySQL database.
DB_HOST=127.0.0.1: This indicates the local machine, i.e. Your database server is on your own computer. This is the IP address or domain name of our server if you are using a remote server.
DB_PORT=3306: This is the default port number of MySQL, which is usually used by MySQL servers.
DB_DATABASE=laravel_crud: This specifies which database your application will use. Here the database is named laravel_crud.
DB_USERNAME=root: This is the username of the user who will access the database. Here root is being used, which is the default MySQL user.
DB_PASSWORD=: The password field is provided here, but no password is specified (i.e. empty). If a password was required, it would have to be entered here.
In short, this code specifies the settings for connecting your Laravel application to the MySQL database.

CREATE required files

In this step, we create "model", "migrations", "controller" and "view" files using Laravel commands.

                           
  php artisan make:model crud/CrudModel -m
  php artisan make:controller crud/CrudController -r
                               

php artisan make:model crud/crudModel -m

This command creates a model, which is used to interact with the database. Also, the -m flag creates a migration file that defines the structure of the table (such as columns and data types). The model is named CrudModel and is saved inside the Crud folder.

php artisan make:controller crud/crudController -r

This command creates a controller, which is used to handle HTTP requests. The -r flag creates a resourceful controller, which has CRUD (create, read, update, delete) methods already defined. Its name is CrudController and it is also saved inside the Crud folder.

CREATE view files

In this step, HTML code is written in files with the extension ".blade.php"

Write Code

In this step, code is written to save (create) the data. I created some files which are "layout.blade.php," "form.blade.php," "edit.blade.php," "show.blade.php," "migration file," "model file," "controller file" etc. These files contain code to save and display data etc.

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

This code is part of a database migration used to create a table in Laravel. The migration creates a table named crude_table, which has 6 columns: id (which is the primary key), name, email, contact, profile (the user's profile image), and password. The timestamp() function automatically adds the created_at and updated_at columns. If this migration ever needs to be reversed, the down method in the dropIfExists function will delete the table.

Model File


    <?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 code is a Laravel model class that works with crud_table. The class uses the hasFactory attribute which helps generate data from the factory. The model name is CrudModel, and it is associated with a database table named crud_table. The protected $fillable property contains the columns that can be safely filled via mass assignment, such as name, email, contact, profile, and password. This means we can easily create and update fields.

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') }}">
        <style>
            body {
                background:url('{{ asset('crud_asset/bg/img4.webp') }}');
                background-repeat: no-repeat;
                background-position: center;
                background-attachment: fixed;
                background-size: cover;
                max-height:100vh;

            }
        </style>
    </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 code is of a custom HTML page that is used in the Laravel network. First, the <head> section contains the meta information of the page such as the fragment set, viewport monitor (which makes it mobile-friendly), and the page title "Crud - Laravel". Also, the Bootstrap CSS is linked which makes the page stylish and responsive. Another custom CSS file is also linked called style.css.

Then, a stretcher image is set for <style> inside body tag which is loaded from crud_asset/bg/img4.jpg. This image is fixed on the photographer in the photographer center and also on its student page this image remains on its marketing. What makes the design of this page more attractive and user friendly.

Lastly, @yield('content') is given inside the <body> tag which is part of the Laravel Blade templating engine. This attached content is used to render the page. Bootstrap and jQuery libraries are included at the bottom of the page. Cospace tags are included at the bottom of the page to improve the page's interactivity and responsiveness. A custom style.js file is also included for document use.

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
                   

This code is to create a simple form in which the user can submit their personal information. This form is written in the Laravel framework and has different fields such as name, email, contact number, password, and profile picture. The action URL of the form is {{route('submit.form')}}, which will submit the form and then the data will be sent to the server.

Laravel crud operation

Validation is also provided for each input field inside the form. If the user enters any wrong information, he will see an error message. For example, if the username, email, contact number, or password is not in the correct format, then a red error message will be displayed below it. For this, Laravel's built-in error handling has been used, in which @error directive has been used.

Finally, this form is submitted via the POST method and @csrf directive has also been used to avoid CSRF (Cross-Site Request Forgery) attack. When the form is submitted a button is given which the user can click to submit his information.

Route File


    <?php

    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\crud\CrudController;

    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider and all of them will
    | be assigned to the "web" middleware group. Make something great!
    |
    */

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

    Route::get('/', [CrudController::class, 'index'])->name('form');
    Route::post('/submit_data', [CrudController::class, 'submit'])->name('submit.form');


This code defines web routes in Laravel. The first route (Route::get('/')) is for the home page of the website (/) which calls the index method of the CrudController. This method displays the form to the user. The second route (Route::post('/submit_data')) is for submitting the form data which will call the submit method of CrudController and handle the data. Both routes are given a name, the first one is 'form' and the second one is 'submit.form' which we can easily reference in our application.

Controller File


    <?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 code is part of a Laravel controller named CrudController. There are important methods in the controller: index and submit. The index method's job is to view the form. When the user visits the home page, this method returns the crud.pages.form view which shows the form where the user can submit his details.

The submit method handles the data of the form. When the user submits the form, the first thing that happens is data validation. Like, the username must have 3 characters, the email must be unique, the contact number must be 10 digits, the password must be at least 8 characters, and the confirm password must be equal to the user password. Apart from this, the format of the profile image is also checked (only JPG, PNG, WEBP, yes JPEG is allowed).

If the validation passes, the controller is to rename the image and store the file in a specific folder (/crud_asset/image/). After that, the CrudModel is saved to the database using the form data. The password is hashed so that it is secure. If the data is saved successfully, the user is given a redirect with a success message. If something goes wrong, the form is shown again with an error message.

Thus, this controller handles the form data, validates it, saves the image, and adds the record to the database.

Post a Comment

Previous Post Next Post

Recent in Technology