Laravel Crud Operation - Update Data

In this article we will cover the third part of CRUD operations, in which we will learn how to update data. You will learn how to modify existing data and update your database."

Laravel Crud Operation

let's see down the step of the update the data in the Laravel

Route Setup


    <?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');
    Route::get('/crud/data', [CrudController::class, 'showdata'])->name('view.data');
    Route::get('/updateform/{id}', [CrudController::class, 'updateview'])->name('updateview.data');
    Route::post('/updatesubmit/{id}', [CrudController::class, 'updatedate'])->name('updatesubmit.data');


Get Source Code


The first route Route::get('/updateform/{id}', [CrudController::class, 'updateview'])->name('updateview.data'); handles a GET request. When a user visits this URL (/updateform/{id}), this route calls the updateview function of CrudController. {id} is a placeholder that identifies a specific resource (such as a user or item). This function is usually used to display a form in which the user gets the option to update the data.


Second route Route::post('/updatesubmit/{id}', [CrudController::class, 'updatedate'])->name('updatesubmit.data'); Handles a POST request. This route is triggered when a user submits a form. In this also the specific resource is updated using the {id}. This route calls the update function of the CrudeController, in which the data submitted by the form is processed and updated. This route sends the form data to the server, due to which the database gets updated.


Controller Method


    <?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
    {

        public function updateview($id)
        {
            $update = CrudModel::find($id);
            return view('crud.pages.edit', compact('update'));
        }

        public function updatedate(Request $request, $id)
        {
            $edit_data = CrudModel::find($id);
            if($request->file('userprofile'))
            {
                $imagename = $request->file('userprofile');
                $imagerename = $request->input('username') . '_' . time() . '.' . $imagename->getClientOriginalExtension();
                $located = public_path('/crud_asset/image/');
                $edit_data->name = $request->input('username');
                $edit_data->email = $request->input('useremail');
                $edit_data->contact = $request->input('usercontact');
                $edit_data->profile = $imagerename;
                $edit_data->update();
                if($edit_data)
                {
                    $imagename->move($located, $imagerename );
                    return redirect()->route('view.data')->with('success', 'Record has been update successfully');
                }
                else
                {
                    return redirect()->back()->with('error', 'Record has not been update successfully');
                }
            }
            else
            {
                $edit_data->name = $request->input('username');
                $edit_data->email = $request->input('useremail');
                $edit_data->contact = $request->input('usercontact');
                $edit_data->update();
                if($edit_data)
                {
                    return redirect()->route('view.data')->with('success', 'Record Has Been Successfully Update');
                }
                else
                {
                    return redirect()->back()->with('error', 'Record Has Not Been Successfully Update');
                }
            }
        }
    }


updateView($id): When the user wants to edit a record, this method fetches the record, assigns it the unique ID it needs ($id), and then returns the edit view where the user can edit the record.

update(request, $request, $id): This method updates the data submitted by the user via the form. If the user uploaded their profile picture, the image is stored in a specific folder. If the image is a file, it saves the first image, and then updates the rest of the fields like name, email, and contact number. If there is no image, only the text field is updated. If the record is updated successfully, it redirects with a success message, else returns with an error message.

Laravel Crud Operation

View Setup

You have to create a form in which the user can update his data. The form will have pre-filled data so that the user can easily do whatever update he wants.


    @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 - Edit</h4>
                        </div>
                        <div class="card-body">
                            @if (session('success'))
                                <div class="alert alert-success">
                                    {{ session('success') }}
                                </div>
                            @endif
                            @if (session('error'))
                                <div class="alert alert-danger">
                                    {{ session('error') }}
                                </div>
                            @endif
                            <form action="{{route('updatesubmit.data', ['id' => $update->id])}}" 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="{{$update->name}}">
                                        @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="{{$update->email}}">
                                        @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="{{$update->contact}}">
                                        @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="{{$update->profile}}">
                                        @error('userprofile')
                                            <div class="alert alert-danger">{{$message}}</div>
                                        @enderror
                                    </div>
                                </div>

                                <div class="row m-2">
                                    <div class="col-lg-6">
                                        <button type="submit" class="submitbutton">SUBMIT</button>
                                    </div>
                                </div>
                            </form>

                            <img src="{{asset('crud_asset/image/'). '/' .$update->profile}}" alt="" style="height:100px;" class=" mt-2 img-fluid img-thumbnail">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endsection


This code is taken to create an “Edit” page of CRUD (Read, Update, Delete) operation using Laravel framework. It has a form in which builders can update their details. The form has fields, such as “Name”, “Email”, “Contact Number”, and “Profile”. When the user updates his details and submits, his data is sent to the server where it is searched.

The code also contains @id field, use it to see the success or error. If the form is submitted successfully, then the successful message is displayed, and if any error comes, then the error message is displayed. Check the validation in all the form fields, like if any field is empty or incorrect, please notify.

The image which is getting uploaded in the form also takes information of the time of update. The image included in the list is painted from the server which users can see their current image. The main purpose of the code is to update the user's data which can be managed easily.



Post a Comment

Previous Post Next Post