Every developer has used object-oriented programming (OOP) at some time in their career, and it is considered to be a fundamental programming paradigm. When using OOPs, the primary goal is to securely bind together data and the functions that perform operations on them, preventing any other portion of code from accessing that information.

In this blog, I will explain what is OOPs concept, principles of the OOPs concept, and how to create a CRUD operation with laravel, which is well known in web development.

What is OOPs?

Object-Oriented  Programming system (OOPs) is an approach to software development that models applications around real-world objects such as employees, cars, bank accounts, etc. 

Two of the general OOPs concepts in Java are class and object. A class defines the properties and methods of a real-world object, while an object is an occurrence of a class.

There are three basic components of object orientation. These are:

  • Object oriented analysis – functionality of the system
  • Object oriented designing – architecture of the system
  • Object oriented programming – implementation of the application

Major Principles of OOP

Let me introduce you to the three major principles of OOP. 

Encapsulation

Reducing the complexity in software development is the main purpose of encapsulation. It is done so by hiding the implementation details and revealing only the operations. Thus using a class becomes easier.

Through methods like get and set, access to the class variables makes the class easy to maintain and flexible so that the internal state of an object is protected. This way, without worrying about breaking the code, the internal implementation of the base class can be changed. 

Inheritance

Re-usability is the main purpose of inheritance. Here, it is concerned with the relationship between classes. Various classes can use the methods defined to inherit from a parent class. 

For instance, where you have to provide common functionality like adding, updating, and deleting data from the database, inheritance can be quite useful. 

Polymorphism

To simplify maintaining applications and make them more extendable is the purpose of polymorphism. It is concerned with having different implementation ways for a single form. 

How to create a CRUD Operation with Laravel?

Laravel is open source web application framework with expressive, elegant syntax. A web framework provides a structure and starting point to creating an application, letting you focus on the main aspects. Laravel is ideal for server-side operations, and you can combine it with frontend frameworks like React to build a React CRUD frontend. As a result, you can make applications dynamic and interactive for end-users.

As a PHP framework, Laravel supports object-oriented programming. The model view controller(MVC) design pattern is used by Laravel to create its applications. 

PHP supports object-oriented programming, which is both quicker and easier to perform than traditional programming languages. Php4 was the first version of PHP to include object-oriented programming (OOP). When it comes to coding, object-oriented programming is a technique that allows developers to arrange the data and structure of an application into classes.

We will now see how to create a CRUD operation (Create , Read , Update and Delete)

To start with any programming language, you should have basic knowledge of whichever language you are going to start. Therefore, I am starting with Laravel, which is very famous in web development.

Step 1: Install the Laravel Project

The first step is to install the Laravel project. You can download any version of Laravel. Here, I have shared below the official website of Laravel: 

https://laravel.com/docs/8.x/installation#why-laravel

You can install it with composer, or you can just install the folder and keep it in your htdocs folder. 

You can download the composer by using the steps given in the below link:

https://getcomposer.org/download

You may verify if Composer is installed in your system by opening a CMD (command prompt) and typing composer, and pressing enter. The Composer will appear to you as follows:

How to create a crud operation with laravel step 1

Now you are ready to install the Laravel project. To do so, please follow the steps below:

Firstly have to visit Laravel's official website.

Here you can choose any version which you want to work with :

Laravel installation

Select your app version and scroll down to you will see the command as shown below:

composer create-project –prefer-dist laravel/laravel blog “5.8.*”

composer create project

Please use this command in your cmd panel, and once you hit this command, your project will start downloading. 

Make sure you are downloading in htdocs folder:

downloading in htdocs forlder

It will take a couple of minutes, and once the project is downloaded, you will see a folder structure as shown in the image below:

downloaded project

Step 2: Update Database Configuration

In the second step, you will make a database configuration. For example, database name, username, password, etc., for your CRUD application of Laravel 5.8. So now you have to open .env file and fill in all details as shown below:

Update Database Configuration 1
Update Database Configuration 2

Step 3: Create the Table

You are going to create a CRUD application for the product. So, you have to create migration for “products” table using Laravel 5.8 PHP artisan command.

First, run this command in your project directory :  

php artisan make:migration create_products_table –create=products

create the table

Here you can see your recently created migration:

created migration

Open your migration file and paste the below mentioned : 

migration file

<?php

use IlluminateSupportFacadesSchema;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateDatabaseMigrationsMigration;

class CreateProductsTable extends Migration

{

    public function up()

    {

        Schema::create(‘products', function (Blueprint $table) {

            $table->increments(‘id');

            $table->string(‘name');

            $table->text(‘detail');

            $table->timestamps();

        });

    }

    public function down()

    {

        Schema::dropIfExists(‘products');

    }

}

Now you have to run the command :php artisan migrate. And once you run this command, your table will be created in the database. 

Step 4: Create a Resource Route

Here, we need to add a resource route for the product CRUD application. So to do this, open your “routes/web.php” file and add the following route.

routes/web.php 

create resource route

Route::resource(‘products','ProductController');

Step 5: Create Controller and Model

In this step, we should now create a new controller as ProductController. So run the command below and create a new controller. Use the new controller to create a resource controller.

php artisan make:controller ProductController –resource –model=Product

<?php

namespace AppHttpControllers;

use AppProduct;

use IlluminateHttpRequest;

class ProductController extends Controller

{

    public function index()

    {

        $products = Product::latest()->paginate(5);

        return view(‘products.index',compact(‘products'))

            ->with(‘i', (request()->input(‘page', 1) – 1) * 5);

    }

    public function create()

    {

        return view(‘products.create');

    }

    public function store(Request $request)

    {

        $request->validate([

            ‘name' => ‘required',

            ‘detail' => ‘required',

        ]);

        Product::create($request->all());

        return redirect()->route(‘products.index')

                        ->with(‘success','Product created successfully.');

    }

    public function show(Product $product)

    {

        return view(‘products.show',compact(‘product'));

    }

    public function edit(Product $product)

    {

        return view(‘products.edit',compact(‘product'));

    }

    public function update(Request $request, Product $product)

    {

        $request->validate([

            ‘name' => ‘required',

            ‘detail' => ‘required',

        ]);

        $product->update($request->all());

        return redirect()->route(‘products.index')

                        ->with(‘success','Product updated successfully');

    }

    public function destroy(Product $product)

    {

        $product->delete();

        return redirect()->route(‘products.index')

                        ->with(‘success','Product deleted successfully');

    }

}

Your model will look as shown in the image below.

model

Step 6: Create Blade Files

Folder:  resources/views/products/layout.blade.php

resources/views/products/index.blade.php

create blade files 1
create blade files 2

resources/views/products/create.blade.php

@extends(‘products.layout')

@section(‘content')

<div class=”row”>

    <div class=”col-lg-12 margin-tb”>

        <div class=”pull-left”>

            <h2>Add New Product</h2>

        </div>

        <div class=”pull-right”>

            <a class=”btn btn-primary” href=”{{ route(‘products.index') }}”> Back</a>

        </div>

    </div>

</div>

@if ($errors->any())

    <div class=”alert alert-danger”>

        <strong>Whoops!</strong> There were some problems with your input.<br><br>

        <ul>

            @foreach ($errors->all() as $error)

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

            @endforeach

        </ul>

    </div>

@endif

<form action=”{{ route(‘products.store') }}” method=”POST”>

    @csrf

     <div class=”row”>

        <div class=”col-xs-12 col-sm-12 col-md-12″>

            <div class=”form-group”>

                <strong>Name:</strong>

                <input type=”text” name=”name” class=”form-control” placeholder=”Name”>

            </div>

        </div>

        <div class=”col-xs-12 col-sm-12 col-md-12″>

            <div class=”form-group”>

                <strong>Detail:</strong>

                <textarea class=”form-control” style=”height:150px” name=”detail” placeholder=”Detail”></textarea>

            </div>

        </div>

        <div class=”col-xs-12 col-sm-12 col-md-12 text-center”>

                <button type=”submit” class=”btn btn-primary”>Submit</button>

        </div>

    </div>

</form>

@endsection

resources/views/products/edit.blade.php

@extends(‘products.layout')

@section(‘content')

    <div class=”row”>

        <div class=”col-lg-12 margin-tb”>

            <div class=”pull-left”>

                <h2>Edit Product</h2>

            </div>

            <div class=”pull-right”>

                <a class=”btn btn-primary” href=”{{ route(‘products.index') }}”> Back</a>

            </div>

        </div>

    </div>

    @if ($errors->any())

        <div class=”alert alert-danger”>

            <strong>Whoops!</strong> There were some problems with your input.<br><br>

            <ul>

                @foreach ($errors->all() as $error)

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

                @endforeach

            </ul>

        </div>

    @endif

    <form action=”{{ route(‘products.update',$product->id) }}” method=”POST”>

        @csrf

        @method(‘PUT')

         <div class=”row”>

            <div class=”col-xs-12 col-sm-12 col-md-12″>

                <div class=”form-group”>

                    <strong>Name:</strong>

                    <input type=”text” name=”name” value=”{{ $product->name }}” class=”form-control” placeholder=”Name”>

                </div>

            </div>

            <div class=”col-xs-12 col-sm-12 col-md-12″>

                <div class=”form-group”>

                    <strong>Detail:</strong>

                    <textarea class=”form-control” style=”height:150px” name=”detail” placeholder=”Detail”>{{ $product->detail }}</textarea>

                </div>

            </div>

            <div class=”col-xs-12 col-sm-12 col-md-12 text-center”>

              <button type=”submit” class=”btn btn-primary”>Submit</button>

            </div>

        </div>

    </form>

@endsection

resources/views/products/show.blade.php

create blade files 3

Now that you have done with all code, all you need to do is just run one command in your cmd. 

run command on cmd

Wrapping up

In this blog, I introduced you to the OOPs concept, a fundamental programming paradigm. The main principles of OOPs were also explained. The blog also explained the step-by-step procedure to create a CRUD operation in Laravel.  

Large programs are tough to write, but if the development and design teams adhere to object-oriented principles, they will be able to create better designs with fewer defects. Because each object exists on its own, it helps to increase the program's modularity.

I hope this blog was helpful for you. And if you are looking for web design or web development services, feel free to contact us!

Frequently Asked Questions

Polymorphism allows objects of different classes to be treated as objects of a common superclass. This concept enables you to write more flexible and reusable code by allowing you to work with objects in a generic way without needing to know their specific types.

Overloading and overriding are two fundamental concepts in object-oriented programming (OOP) that involve methods in classes. Method overloading is a feature in OOP where you can define multiple methods in the same class with the same name but different parameter lists (i.e., a different number or types of parameters).
Method overriding is a feature in OOP where a subclass provides a specific implementation of a method that is already defined in its superclass. The subclass's method has the same name, return type, and parameters as the method in the superclass.

Abstraction is the process of simplifying complex reality by modeling classes based on the essential properties and behaviors an object should have while ignoring or hiding unnecessary details. It involves defining the essential characteristics of an object and ignoring the non-essential ones.
Encapsulation is the concept of bundling data (attributes) and methods (functions or operations) that operate on that data into a single unit called a class. It also involves restricting direct access to some of an object's components and only providing access through well-defined interfaces (public methods).

A constructor is a special type of method or function that is automatically called when an object of a class is created or instantiated. The primary purpose of a constructor is to initialize the object's attributes (also known as fields or properties) and perform any necessary setup or configuration.