Showing posts with label laravel. Show all posts
Showing posts with label laravel. Show all posts

Saturday, 3 September 2022

7 Reasons To Use Laravel For Web App Development

7 Reasons To Use Laravel For Web App Development


There are various PHP frameworks around, including. Laravel. However, with its unparalleled capability to deliver immersive and engaging experiences to users, it has become one of the most preferred choices in the lot.

Over 688,027 live websites currently use Laravel. Despite being over a decade old, its ease, simplicity, and flexibility have contributed to Laravel being called one of the best MVC-based PHP frameworks. Simply put, Laravel has every ingredient for a streamlined development, as long as you know how to utilize it. That’s a major reason why Laravel developers are so in-demand currently (which is why businesses choose to hire a web application development company or other low-cost nations).

But why is Laravel so popular still? Let’s take a look at the biggest reasons.

1. It Is Based On MVC Architecture


MVC stands for model view controller and is a means of web development that provides a clear separation between the model view that a user sees of the web application and its business logic running in the background. With Laravel’s MVC architecture, the data associated with the web app gets split into logical files.

Such distinctions in data files make it easier to locate a required file in a large project, change views without affecting the model, and scale your web app along with your business without hassles.

Laravel also helps with excellent database management by enabling you to easily create, delete, and redo it without the need to run an SQL query or log into a console. It also helps with data maintenance team work with the continuous support of table creation and updating.

2. Excellent Traffic Handling Capabilities


Who doesn’t want their web application to gain more traffic and bring in more conversions? Well, a business whose web app cannot handle that increased traffic is one candidate. Such a business will lose customers because its app won’t be able to cope with the traffic load, leading to freezes, slow load times, crashes, and data loss.

All of those scenarios will turn interested customers away from the business.

With the PHP Laravel Framework, you get a message queue system that balances the load. This makes traffic management effective by providing a unified API across various queue backgrounds. These queues let you put off a time-consuming task, increasing the speed of web requests of the web app. Thus, the web server is kept healthy.

3. Automated Task Scheduling and Execution


Every online application requires a task scheduling system to automate tasks as needed. For instance, sending subscribers emails, notifying app users, or simply cleaning out databases to speed up online apps.

In the past, a Cron entry had to be created by web developers for each operation they wished to schedule. By utilizing Laravel's automatic command scheduler, you can, however, avoid this hassle. With only one Cron entry needed on your server, you can rapidly and expressively construct your command schedule within the Laravel framework itself. This Laravel framework feature not only boosts the performance and speed of your online application but also lowers your hosting costs.





4. Mail Services Integration


If a modern web framework does not provide mail integration, it is unacceptable. Every essential activity or action by the user should trigger an email notification from the web app. Swiftmailer, a package included with Laravel, allows for simple and clear API setups for unique email accounts.

It also offers several drivers that quickly send messages using local or cloud-based services. SMTP, Mailgun, Mandrill, SparkPost, Amazon SES, PHP's "mail" function, and "Sendmail" are a few examples. Thus, with the help of Laravel, your email-based communication issues are resolved even before they can crop up.

5. Robust Security


A web app is useless if it doesn’t come with top-notch security features to protect both company and user data. Laravel creates web apps that contain end-end security that prevents not just unauthorized access but also secures the data very robustly. It does this with the use of “Guards” and “Providers.” They help authenticate a user and then take them back once data is retrieved.

Laravel marks the creation of access control mechanisms easy as it uses only a single command to help with Login, Registration, and Password Reset. It also helps ease the organization of authorization logic and the control of access to resources. This is why it has earned the title PHP authentication framework.

It also stores passwords in a hashed format to obscure them from prying eyes. The Bcrypt hashing process ensures added security by creating a new hash each time. Ready-made SQL statements are also present to stop injection attacks. These measures make the database very secure along with the traffic flow.

6. Eased Construction with Object-Oriented Libraries


The Laravel framework comes with many pre-installed features and built-in object-oriented libraries. This is the main distinction between Laravel and other PHP frameworks.

There are some amazing qualities like

  • Password resetting
  • Active user monitoring
  • Cross-site request forgery (CSRF) prevention provided by integrated authentication libraries is another fantastic feature. ( This is a malicious exploit that was carried out on behalf of a verified user).
  • By producing a CSRF token for each session, it defends against this attack. Consequently, it makes it impossible to access.

7. Full-fledged Community Support


A framework isn’t useful if a developer can’t find the support they need to create the requisite web app. That is not the case with Laravel, as it has a vast community of professional and amateur developers who can address any query regarding it.

An example of this is Laracasts, which is a paid+free platform that gives you the necessary support to learn and utilize the framework. There are video tutorials that carry one through the development process from the first to the last step. Hence, with Laravel, you’re never far away from help.

In Conclusion


Web applications have revolutionized how the world communicates and consumes information, and that transformation is only accelerating. Newer options like Progressive Web apps are taking over the scene, which brings more advantages to business than traditional applications. Amidst all these evolutions, businesses must be ready to adapt. The best way to do so is with an experienced partner that understands your concerns and can deliver on your requirements.

Hire Laravel developers in India, and you will have a strong web app development process that secures your present need and makes you future-ready too. If you outsource the process to a low-cost region, like India or the Philippines, you can get the additional advantage of cost reduction, which is bound to boost your ROI.

How Laravel Framework Transforms Web Development?

If you have invested in a complex application, choosing the right platform for web development can bring in the distinction in terms of quality and functionality for the application. And when it comes down to selecting the right platform for a complex web development project, the PHP-based Laravel web framework emerges as an appealing choice.

In recent years, the open-source Laravel framework has been coming up on the list of most trusted and dependable frameworks for web development, especially Laravel Development Services. Laravel is an open-source platform that is self-equipped with several advanced and stable features making itself a standout performer among the other PHP frameworks.

Laravel at a Glance


Laravel framework is a web structure dedicated to helping web developers for developing a web application using web APIs, web services, and web resources for several purposes. Given its model-view-controller (MVC) architecture, the Laravel framework is well-equipped to deliver precise and rapid results. Laravel comes with comprehensive possibilities of dealing with the advanced elements with an active community of web developers and users.

Laravel web app development utilizes a framework with expressive and elegant syntax that makes web development faster, easier, and enjoyable by banishing all the difficulties associated with complex PHP code handling.

And, now that you know all about Laravel, you should also know the reasons why the Laravel framework is the best choice for web development. There are several reasons for choosing Laravel as the platform for web development by your organization:

1. Security:


Security is the most prominent factor why you should prefer Laravel as a platform for web development. It is capable of extending a significant level of security parameters that are usually not found in other frameworks.

The CSRF tokens in Laravel offer an ability of checking every request on the POST. Not only this, it provides protection from any person attempting to change POST to GET the request.

This ensures additional protection from threats. The feature of authentication and authorization in Laravel leverage complete access to owners for configuring the security features.

2. Database Migration:


The presence of a database migration feature in the Laravel framework is helpful in reducing the risk of data loss. The database syncing gets easier in Laravel app development.

It allows developers to share the database easily with the other members of the team. So, it proves to be more time-saving and efficient for the web-development team.

3. Lengthy Programming gets Easy:


Another reason that makes Laravel a great option for web development is that it allows developers to access Laracasts, which is a specialized tool for learning and practice.

These tools offer tutorials that help developers resolving complicated issues through coding. The content on the platform is created by the experts to provide structured instructions enabling optimized solutions development according to the needs of the business.





4. Object-oriented Libraries:


Laravel comes with support to a multitude of development environments and connect itself depending the platform on which the app runs. This gets possible because of the libraries which are integrated into the Laravel web development platform.

Moreover, Laravel libraries are equipped with auto-complete features, which don’t exist in other PHP frameworks. These object-oriented libraries leverage easy-to-use tools for developers and the classified nature of the framework makes it a perfect choice for developers to develop more responsive and modular applications.

5. MVC Support:


A majority of web development platforms are not capable of this as they fail to deliver support to MVC whereas, with Laravel, the support to MVC is explicit.

MVC architecture helps improve the overall performance of the app, renders better documentation, and leverages multiple functionalities within the single application, and this makes Laravel web development a lucrative choice for businesses.

6. Blade Templating Engine:


The Blade Templating Engine is a distinctive feature that exists in the Lathe ravel framework only. This engine is intuitive and functions in an effective manner with typical PHP/HTML code.

Also, developing impressive layouts is feasible as the templates are not heavy and complex. It helps developers to leverage the widgets of CSS, helps them create fantastic appeal, and cut down the loading time of the website. It ultimately results in an improvement in the search engine ranking.

7. Community Support:


Laravel is an open-source framework backed up by a massive community of experts. So, at the time of being struck at any point during the process of web development, help or assistance can easily be obtained from the community, and resolving the issue becomes a faster and easier task. The possibility of delays can be reduced to a minimum by this.

8. Unit Testing:


Unit-testing feature is also available in the Laravel framework. This ensures easy testing and enhanced chances of deployment of a flawless product. Not only this, but various other tests are also possible with Laravel which is helpful in avoiding any unexpected breakdowns if a developer attempts any new update at any point in time on the project.

With the above insights, it is clear that Laravel can be proved a great choice for web development for any business. Collaborating with a top Laravel development company can leverage the benefits of this technology for your business too.

A Custom Laravel eCommerce Platform can be a solution to so many issues with your online business website and applications. So many companies in the market are working on developing Laravel-based platforms but choosing the best Laravel development company only can leverage the advantages for you.

So, it is the right time for you to take Laravel web development services for your business growth and expansion, and for this, a reputed Laravel development agency should be your choice. Look for one that is all set to create a custom application that is capable of responding to your business needs aiming to resolve the challenges you face and add value to your website and business.

Authors Bio


Alyda Martha

I am tech enthusiastic and an online business freak. I help people to learn trends and grow business. Currently, Helping Bytes Technolabs INC to grow and collaborate. Happy soul and open heart personality.

Wednesday, 3 August 2022

Custom Auth Login Registration Logout in Laravel 9

Laravel 9 Custom Login Registration Video Tutorial Part 1



Laravel 9 Custom Login Registration Video Tutorial Part 2



Laravel 9 Custom Login Registration Video Tutorial Part 3



This is Laravel 9 Custom Login Logout and Registration Tutorial, so by this tutorial, we will show you how to create custom Authentication Login Logout and Registration in Laravel 9 Application. So here we will use Laravel 9 Custom Login and Registration.

If you have use Laravel framework for your web development then Laravel 9 framework has provides in built Authentication by using jetstream and UI package. But in some condition we have to create our own Login, Regstration, dashboard and logout. So This tutorial will help you to create custom Login Registration in Laravel 9 framework and here in this tutorial we will create step by step custom login and registration page in Laravel 9 application.

  1. Install Laravel 9 Application
  2. Make Database Connection
  3. Create Controller
  4. Create View Blades Files
  5. Set Controller Method Route
  6. Run Laravel 9 Application

Custom Auth Login Registration Logout in Laravel 9




Step 1 : Install Laravel 9 Application


First for Crate Custom Login and Registration in Laravel 9 framework, then first we have to download fresh Laravel 9 application. So for this, we have goes to command prompt and run following command. This command will create custom_login directory and under that directory, it will download Laravel 9 application.


composer create-project laravel/laravel custom_demo


Step 2 : Make Database Connection


After download Laravel 9 Application for Create Custom Login and Registration, now we have to make MySQL database connection, So we have to open .env file and under this file, we have to define following MySQL database configuration which you can seen below and it will make MySQL database connection in Laravel 9 Application.


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


After Make MySQL database connection, now we need to create users table in connected MySQL database. So we goes to command prompt and run following command. This command will create users tables in MySQL database.


php artisan migrate


Step 3 : Create Controller


Now in this steps for handle http request of Laravel 9 Custom Login and Registration Application, we have to create controller. So for this, we have goes to command prompt and run following command, which will create SampleController.php file under app/Http/Controllers directory and under this file, we have to add following code.

app/Http/Controllers/SampleController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Hash;
use Session;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class SampleController extends Controller
{
    function index()
    {
        return view('login');
    }

    function registration()
    {
        return view('registration');
    }

    function validate_registration(Request $request)
    {
        $request->validate([
            'name'         =>   'required',
            'email'        =>   'required|email|unique:users',
            'password'     =>   'required|min:6'
        ]);

        $data = $request->all();

        User::create([
            'name'  =>  $data['name'],
            'email' =>  $data['email'],
            'password' => Hash::make($data['password'])
        ]);

        return redirect('login')->with('success', 'Registration Completed, now you can login');
    }

    function validate_login(Request $request)
    {
        $request->validate([
            'email' =>  'required',
            'password'  =>  'required'
        ]);

        $credentials = $request->only('email', 'password');

        if(Auth::attempt($credentials))
        {
            return redirect('dashboard');
        }

        return redirect('login')->with('success', 'Login details are not valid');
    }

    function dashboard()
    {
        if(Auth::check())
        {
            return view('dashboard');
        }

        return redirect('login')->with('success', 'you are not allowed to access');
    }

    function logout()
    {
        Session::flush();

        Auth::logout();

        return Redirect('login');
    }
}






Step 4 : Create View Blades Files


In this steps, we need to create blade views file for display custom Login Registration page output in the browser. So here we have goes into resources/views directory and under this we have to create blades files for display login, registration and dashboard page files and we will also create master template files also. Below we will create files one by one.

resources/views/main.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 Custom Login Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <nav class="navbar navbar-light navbar-expand-lg mb-5" style="background-color: #e3f2fd;">
        <div class="container">
            <a class="navbar-brand mr-auto" href="#">Laravel 9 Custom Login Registration</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                    
                <ul class="navbar-nav">
                    @guest

                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('registration') }}">Register</a>
                    </li>

                    @else

                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('logout') }}">Logout</a>
                    </li>

                    @endguest
                </ul>
                
            </div>
        </div>
    </nav>
    <div class="container mt-5">

        @yield('content')
        
    </div>
    
</body>
</html>


resources/views/login.blade.php

@extends('main')

@section('content')

@if($message = Session::get('success'))

<div class="alert alert-info">
{{ $message }}
</div>

@endif

<div class="row justify-content-center">
	<div class="col-md-4">
		<div class="card">
			<div class="card-header">Login</div>
			<div class="card-body">
				<form action="{{ route('sample.validate_login') }}" method="post">
					@csrf
					<div class="form-group mb-3">
						<input type="text" name="email" class="form-control" placeholder="Email" />
						@if($errors->has('email'))
							<span class="text-danger">{{ $errors->first('email') }}</span>
						@endif
					</div>
					<div class="form-group mb-3">
						<input type="password" name="password" class="form-control" placeholder="Password" />
						@if($errors->has('password'))
							<span class="text-danger">{{ $errors->first('password') }}</span>
						@endif
					</div>
					<div class="d-grid mx-auto">
						<button type="subit" class="btn btn-dark btn-block">Login</button>
					</div>
				</form>
			</div>
		</div>
	</div>
</div>

@endsection('content')


resources/views/registration.blade.php

@extends('main')

@section('content')

<div class="row justify-content-center">
	<div class="col-md-4">
		<div class="card">
		<div class="card-header">Registration</div>
		<div class="card-body">
			<form action="{{ route('sample.validate_registration') }}" method="POST">
				@csrf
				<div class="form-group mb-3">
					<input type="text" name="name" class="form-control" placeholder="Name" />
					@if($errors->has('name'))
						<span class="text-danger">{{ $errors->first('name') }}</span>
					@endif
				</div>
				<div class="form-group mb-3">
					<input type="text" name="email" class="form-control" placeholder="Email Address" />
					@if($errors->has('email'))
						<span class="text-danger">{{ $errors->first('email') }}</span>
					@endif
				</div>
				<div class="form-group mb-3">
					<input type="password" name="password" class="form-control" placeholder="Password" />
					@if($errors->has('password'))
						<span class="text-danger">{{ $errors->first('password') }}</span>
					@endif
				</div>
				<div class="d-grid mx-auto">
					<button type="submit" class="btn btn-dark btn-block">Register</button>
				</div>
			</form>
		</div>
	</div>
</div>

@endsection('content')


resources/views/dashboard.blade.php

@extends('main')

@section('content')

<div class="card">
	<div class="card-header">Dashboard</div>
	<div class="card-body">
		
		You are Login in Laravel 9 Custom Login Registration Application.
	</div>
</div>

@endsection('content')


Step 5 : Set Controller Method Route


Under this step, we need to create custom route for SampleController.php files method. So we need to open routes/web.php file and under this file we have to all following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\SampleController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::controller(SampleController::class)->group(function(){

    Route::get('login', 'index')->name('login');

    Route::get('registration', 'registration')->name('registration');

    Route::get('logout', 'logout')->name('logout');

    Route::post('validate_registration', 'validate_registration')->name('sample.validate_registration');

    Route::post('validate_login', 'validate_login')->name('sample.validate_login');

    Route::get('dashboard', 'dashboard')->name('dashboard');

});



Step 6 : Run Laravel 9 Application


This is last step of Laravel 9 Custom Login, Registration and Logout Application and after follow all above steps, now for check output in the browser, we have to start Laravel server. So for this we have goes to command prompt and run following command.


php artisan serve


So after run this command it will start Laravel server and provide us base url of our Laravel 9 Custom Login Registration Application. So we have to copu that url and open in browser for check output in the browser. So for check demo of Laravel 9 Custom Login Registration application, we have to open following url in the browser.


http://127.0.0.1:8000/login


And lastly, if you have follow this tutorial step by step, then you can able to build custom Login Registration page in Laravel 9 Framework from scratch. We hope this tutorial will help you and you can something learn new things from this tutorial. So best of Luck for this Laravel 9 Custom Login Registration tutorial.





Laravel Security: Top 5 Mistakes Developers Make

Laravel Security: Top 5 Mistakes Developers Make


Committing development errors is not something to be embarrassed about. It could happen to potentially anyone. However, a few errors are expected and effectively avoidable.

If you can realize and avoid those, you might not just eliminate your development at any point but also come out better as a developer.

Laravel is turning out to be increasingly standard. Thus numerous new developers are learning it and building a website with it.

Laravel is a robust PHP framework that offers developers many elements and devices to provide stunning website development services.

Laravel is a Model-View-Controller (MVC) framework, meaning it assists you with coordinating your code into various parts. The Model layer is liable for managing the date, the View layer is answerable for showing the information, and the Controller layer is liable for dealing with the client input.

Laravel likewise offers many features, for example, routing, authentication, database range, and item social planning. These highlights go with Laravel, an extraordinary decision for web application development.

So, this post is planned for those Laravel development company or developers who need to work on their abilities by realizing what not to do. It's OK to commit your errors. However, it's wiser to gain from others' missteps and try not to make them yourself.





HTTPS for Sensitive Data


Developers should layer the application with HTTPS when it includes sensitive data instead of standard HTTP. The utilization of HTTPS becomes a must when there is secret information, which is fundamental to safeguard from vicious assaults.

Double Brace Syntax to the Rescue


Laravel framework is powerless against XSS assaults, so developers must utilize measures fundamentally to stop them. To secure against XSS assaults, developers should take care to utilize a twofold support linguistic structure accessible in the edge format motor.

Prevents SQL Injection


With PDO restricting, Eloquent ORM gives security against SQL Injection. In exact words, it permits no client to change SQL questions' goals.

Authentication Process


Laravel Authentication system is robust and upgrades its general security framework. It utilizes 'providers' and 'guards' to get confirmation and upgrade security highlights.

Assurance against Cross-site Scripting


Laravel framework offers local help to shield the code from XSS attacks. This is programmed elements and starts acts while required, giving round security. It shields databases and projects that have to get away from labels.

Secure your website by avoiding these harmful mistakes that can damage your website. Apply our suggestions while developing your website or hiring laravel development services for your business,

Author Bio


Ashish Jain is the global head at Addweb Solution for handling Offshore Strategic Partnership. Addweb is a leading IT development, consulting and outsourcing company which offers website, app, blockchain, eCommerce development, and digital marketing service. We are agile and dynamic, which gets transmitted through our work.

Saturday, 16 July 2022

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5

Build Laravel 9 CRUD Application with MySQL & Bootstrap 5


In this tutorial, we are going to show you how to make CRUD Application Laravel 9 framework. We will explained you step by step, how can we perform CRUD Operation in Laravel 9 Framework. So if you beginner in Laravel framework then this tutorial will help you to build CRUD Application in Laravel 9 framework, and you will be able to create Laravel 9 CRUN Application. Here under this tutorial, we will use basic example to show you CRUD Operation in Laravel 9.

Recently Laravel has release Laravel 9 framework and in Laravel 9 framework there is several new features and LTS Support. Laravel 9 also introduced an Anonymous Sub Migration also and it also resolved migration class name Collison. One more things Laravel 9 framework has been use PHP 8 version and it has been support PHP string function, which are very useful for string operations. There are many new query builder function has been introduced under Laravel 9 framework which will more convenient when you have work with database operation. So you are learn Laravel framework first time then this tutorial will help you to create CRUD (Create, Read, Update and Delete) Operation in Laravel 9 framework.

In this tutorial, we will create Student CRUD Application in Laravel 9 framework. Under this CRUD Application we will make Application, in which we can Add new Student Data, with student image upload, edit or change existing student data, with form data validation, show single student data on the web page, delete or remove student data from data and fetch all student data from MySQL database and display on the web page in HTML table format with dynamic pagination link. We will also create table in MySQL database from this Laravel 9 application using Laravel 9 Migration, and after this, we will create Controller, Models and views file for student crud application. Under this Laravel 9 crud application we will use Bootstrap 5 library for design web page. You have to following below steps to create CRUD Application in Laravel 9 framework.


Step 1 - Download & Install 9


In the First Steps of Laravel 9 CRUD Application, we have to download and install fresh Laravel 9 Application in our computer. So for this, you have to goes to command prompt and then after goes into directory where you have run PHP 8 script and then after you have to run following command.


composer create-project --prefer-dist laravel/laravel laravel_9_crud


Once we have run this command then it will create laravel_9_crud directory and under this directory it will download and install Laravel 9 Application.

Step 2 - Make Database Connection


After install Laravel 9 application, first we need to create database connection with MySQL database. So for this we have to open .env file and under this file, we need to add MySQL database configuration like MySQL database name, MySQL database user namd and password details. Once we have define this details, then it will make MySQL database connection in Laravel 9 framework. Below you can find MySQL database configuration details.

.env

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


Step 3 - Create MySQL Table using Laravel 9 Migration


Under this step, we have to crate students table under MySQL database from this Laravel 9 Application using Migrations. So first we have to create migration file under Laravel 9 application, so we have to run following command in command prompt.


php artisan make:migration create_students_table --create=students


After run above command then you will find one new file under database/migrations directory. So for we have to open that file and under that file, we have to define following code under that migrations file for create students table in MySQL database.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('student_name');
            $table->string('student_email');
            $table->enum('student_gender', ['Male', 'Female']);
            $table->string('student_image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};



After above code in migration file, now for create table in MySQL database from this Laravel 9 application, so for this, we have to run following command in command prompt and it will migrate MySQL table defination to MySQL database and create students table in MySQL database from this Laravel 9 Application.


php artisan migrate





Step 4 - Create CRUD Model and Controller


Under this step, we have to create Controller and Models file for CRUD Operation. So for this, we have goes to command prompt and run following command, which will create new CRUD StudentController and Student Model class file under Laravel 9 framework.


php artisan make:controller StudentController --resource --model=Student


So after run above command it will create Student.php model class file under app/Models directory and we have to open that file and put following code under that file.

app/Models/Student.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    protected $fillable = ['student_name', 'student_email', 'student_gender', 'student_image'];
}



And after run above command it will also create CRUD Controller with name StudentController.php file under app/Http/Controllers directory.

So this StudentController.php file has been created with seven method by default which you can seen below.

  1. index() - This is root method of this Controller class.
  2. create() - This is method has been used for load Add student form in the browser.
  3. store() - This method has been used for handle Add student data request.
  4. show() - This method has been used for display single student data on the web page.
  5. edit() - This method has been used for load edit student form in the browser.
  6. update() - This method has been receive student update form data request.
  7. destroy() - This method has been used for delete student data from database.

For create CRUD Application, you have to put folliowing code under StudentController.php file.

app/Http/Controllers/StudentController.php app/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Student::latest()->paginate(5);

        return view('index', compact('data'))->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'student_name'          =>  'required',
            'student_email'         =>  'required|email|unique:students',
            'student_image'         =>  'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $file_name = time() . '.' . request()->student_image->getClientOriginalExtension();

        request()->student_image->move(public_path('images'), $file_name);

        $student = new Student;

        $student->student_name = $request->student_name;
        $student->student_email = $request->student_email;
        $student->student_gender = $request->student_gender;
        $student->student_image = $file_name;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function show(Student $student)
    {
        return view('show', compact('student'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function edit(Student $student)
    {
        return view('edit', compact('student'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Student $student)
    {
        $request->validate([
            'student_name'      =>  'required',
            'student_email'     =>  'required|email',
            'student_image'     =>  'image|mimes:jpg,png,jpeg,gif,svg|max:2048|dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000'
        ]);

        $student_image = $request->hidden_student_image;

        if($request->student_image != '')
        {
            $student_image = time() . '.' . request()->student_image->getClientOriginalExtension();

            request()->student_image->move(public_path('images'), $student_image);
        }

        $student = Student::find($request->hidden_id);

        $student->student_name = $request->student_name;

        $student->student_email = $request->student_email;

        $student->student_gender = $request->student_gender;

        $student->student_image = $student_image;

        $student->save();

        return redirect()->route('students.index')->with('success', 'Student Data has been updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Student  $student
     * @return \Illuminate\Http\Response
     */
    public function destroy(Student $student)
    {
        $student->delete();

        return redirect()->route('students.index')->with('success', 'Student Data deleted successfully');
    }
}



Step 5 - Add Service Provider for Bootstrap Pagination


In Laravel 9 framework produce default style pagination link which will not properly display if you have Bootstrap library. So for this, we have to open app/Providers/AppServiceProvider.php and under this file, we have to add Paginator::useBootstrap() code under boot() method for support the bootstrap pagination.

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}



So after adding this code, you Laravel 9 application will display proper pagination link on the web page.

Step 6 - Create Views Blades File


Under this steps, we have to create blades files for display HTML output in the browser. In the Laravel 9 framework, blades files has been stored under resources/views directory. Under this Laravel 9 CRUD Application, we have to create following views blades files.

  1. master.blade.php - This is master template file.
  2. index.blade.php - This file we will used for display MySQL table data on the web page in HTML table format with pagination link.
  3. create.blade.php - This file has been used for load Create Student form on the web page.
  4. show.blade.php - This file has been used for display single student data on the web page.
  5. edit.blade.php - This file has been used for load student edit form in the browser.

Below you can find source code of all blade file.

resources/views/master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 9 CRUD Application</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        
        <h1 class="text-primary mt-3 mb-4 text-center"><b>Laravel 9 Crud Application</b></h1>
        
        @yield('content')
        
    </div>
    
</body>
</html>


resources/views/index.blade.php

@extends('master')

@section('content')

@if($message = Session::get('success'))

<div class="alert alert-success">
	{{ $message }}
</div>

@endif

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Data</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.create') }}" class="btn btn-success btn-sm float-end">Add</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<table class="table table-bordered">
			<tr>
				<th>Image</th>
				<th>Name</th>
				<th>Email</th>
				<th>Gender</th>
				<th>Action</th>
			</tr>
			@if(count($data) > 0)

				@foreach($data as $row)

					<tr>
						<td><img src="{{ asset('images/' . $row->student_image) }}" width="75" /></td>
						<td>{{ $row->student_name }}</td>
						<td>{{ $row->student_email }}</td>
						<td>{{ $row->student_gender }}</td>
						<td>
							<form method="post" action="{{ route('students.destroy', $row->id) }}">
								@csrf
								@method('DELETE')
								<a href="{{ route('students.show', $row->id) }}" class="btn btn-primary btn-sm">View</a>
								<a href="{{ route('students.edit', $row->id) }}" class="btn btn-warning btn-sm">Edit</a>
								<input type="submit" class="btn btn-danger btn-sm" value="Delete" />
							</form>
							
						</td>
					</tr>

				@endforeach

			@else
				<tr>
					<td colspan="5" class="text-center">No Data Found</td>
				</tr>
			@endif
		</table>
		{!! $data->links() !!}
	</div>
</div>

@endsection


resources/views/create.blade.php

@extends('master')

@section('content')

@if($errors->any())

<div class="alert alert-danger">
	<ul>
	@foreach($errors->all() as $error)

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

	@endforeach
	</ul>
</div>

@endif

<div class="card">
	<div class="card-header">Add Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.store') }}" enctype="multipart/form-data">
			@csrf
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
				</div>
			</div>
			<div class="text-center">
				<input type="submit" class="btn btn-primary" value="Add" />
			</div>	
		</form>
	</div>
</div>

@endsection('content')


resources/views/show.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">
		<div class="row">
			<div class="col col-md-6"><b>Student Details</b></div>
			<div class="col col-md-6">
				<a href="{{ route('students.index') }}" class="btn btn-primary btn-sm float-end">View All</a>
			</div>
		</div>
	</div>
	<div class="card-body">
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Name</b></label>
			<div class="col-sm-10">
				{{ $student->student_name }}
			</div>
		</div>
		<div class="row mb-3">
			<label class="col-sm-2 col-label-form"><b>Student Email</b></label>
			<div class="col-sm-10">
				{{ $student->student_email }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Gender</b></label>
			<div class="col-sm-10">
				{{ $student->student_gender }}
			</div>
		</div>
		<div class="row mb-4">
			<label class="col-sm-2 col-label-form"><b>Student Image</b></label>
			<div class="col-sm-10">
				<img src="{{ asset('images/' .  $student->student_image) }}" width="200" class="img-thumbnail" />
			</div>
		</div>
	</div>
</div>

@endsection('content')


resources/views/edit.blade.php

@extends('master')

@section('content')

<div class="card">
	<div class="card-header">Edit Student</div>
	<div class="card-body">
		<form method="post" action="{{ route('students.update', $student->id) }}" enctype="multipart/form-data">
			@csrf
			@method('PUT')
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Name</label>
				<div class="col-sm-10">
					<input type="text" name="student_name" class="form-control" value="{{ $student->student_name }}" />
				</div>
			</div>
			<div class="row mb-3">
				<label class="col-sm-2 col-label-form">Student Email</label>
				<div class="col-sm-10">
					<input type="text" name="student_email" class="form-control" value="{{ $student->student_email }}" />
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Gender</label>
				<div class="col-sm-10">
					<select name="student_gender" class="form-control">
						<option value="Male">Male</option>
						<option value="Female">Female</option>
					</select>
				</div>
			</div>
			<div class="row mb-4">
				<label class="col-sm-2 col-label-form">Student Image</label>
				<div class="col-sm-10">
					<input type="file" name="student_image" />
					<br />
					<img src="{{ asset('images/' . $student->student_image) }}" width="100" class="img-thumbnail" />
					<input type="hidden" name="hidden_student_image" value="{{ $student->student_image }}" />
				</div>
			</div>
			<div class="text-center">
				<input type="hidden" name="hidden_id" value="{{ $student->id }}" />
				<input type="submit" class="btn btn-primary" value="Edit" />
			</div>	
		</form>
	</div>
</div>
<script>
document.getElementsByName('student_gender')[0].value = "{{ $student->student_gender }}";
</script>

@endsection('content')


Step 7 - Set Resource Route


Under this step, we have to add resource route for student crud application. So for set route, we have to open routes/web.php file and under this file, we have to define resource route for Laravel 9 CRUD Application.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\StudentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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


Route::resource('students', StudentController::class);


After adding above code, then it will set route for all method of StudentController.php file.

Step 8 - Run Laravel 9 CRUD Application


When we have follow all above steps, that means our Laravel 9 CRUD Application is ready for check output in the browser. So for check output in the browser, first we need to start Laravel 9 Application server, so for this, we have go to command prompt and run following command.


php artisan serve


So this command will start Laravel server and provide us base url of our Laravel 9 CRUD Application. So we have goes to browser, and type give below URL and view output of Laravel 9 CRUD Application.


http://127.0.0.1:8000/students


So this is complete step by step tutorial on Laravel 9 CRUD Application, so you have follow all above steps then you can able to learn How to perform Insert, Update, Delete and Read MySQL Data Operation in Laravel 9 framework and build CRUD Application Laravel 9 framework with MySQL database and Bootstrap 5 Library.

Laravel 9 CRUD Application Video Tutorial


1 - Load MySQL Data in HTML Table with Pagination Links



2 - Insert or Add Data into MySQL Table



3 - Retrieve MySQL Data & Display on Web page



4 - Update or Edit MySQL Data



5 - Delete or Remove Data From MySQL



Tuesday, 15 February 2022

Visitor Management System Project in Laravel


This is free Laravel project on the Visitor Management System with source code. This Visitor Management System has been developed in Laravel framework, MySQL Database, Bootstrap 5 Library and jQuery. This Visitor Management System has been develop in Laravel Framework and This System is a simple mini project which help us to keeping records of data of Visitors who has visit in our premises, building or office space. This Visitor Management System project has mainly two user, one is an Admin User and and second one is a Sub User.

In this System, Admin can manage all management data like adding sub user, departments, visitor data and view complete analytics of this Visitor Management System and in this system an Admin has play an important role in the management of this system.

For the sub user side, a sub user can add the visitor details like visitor name, address, department, person name to whom to meet, check-in time, reason for visit, checkout time and outing remark of the visitors. This Visitor Management System project is a very simple project and by this system it will makes a convenient way for any organization for stored the records of visitors.

Online Visitor Management System Project in Laravel Framework MySQL with complete Source Code which will be available for Free Download. This Visitor Management System is a Laravel Web based Application which will provides a simple and straight forward check-in and check-out procedure for visitors at a single check-in and check-out data and allowing you to keep track data of Visitor who has comes to your premises.


Visitor Management System Project in Laravel




Visitor Management System Features


These are the following features of Laravel based Online Visitor Management System Project:

  1. Keep & Track Visitor Data
  2. Simple & Clean Visitor Analytics Data with different filter
  3. Export Visitor Data to CSV file format based on different filter
  4. Admin User can view and track all User data in single dashboard
  5. Sub User can view only their data which they has entered
  6. Registration form for set up Admin Account
  7. Common Login page for Admin and Sub User for Log in into Visitor Management System
  8. Admin can Add, Edit and Delete Sub User Data
  9. Admin can Add, Edit, remove and manage department and person data
  10. Admin can change their profile details like name, email and change password
  11. Sub User can Add, Edit, View and Remove Visitor Data
  12. Sub User can enter visitor outing remarks




Visitor Management System Web Technology to be used for build


These are the following Web Technology which we have used for build this Visitor Management System :

Server-side requirement


  • PHP 7.3
  • Laravel 8.75 Framework
  • Yajra Laravel Datatables 9.0
  • MySQL Database

Client-side Requirement


  • jQuery
  • Vanilla JavaScript
  • Ajax
  • jQuery DataTables
  • Bootstrap 5
  • Daterange Picker

Additionally, you can able to download updated sourece from this post after every publishing of video tutorial, so after publishing every part of this Laravel Visitor Management System, you can able to download updated source code from this web page.

Lastly, If you have any query or inputs regarding this Laravel based Visitor Management System, then you can write your query or inputs or feedback in the comment box, we will reply on your comment.









Thursday, 22 July 2021

Autocomplete Search in Laravel 8 using Typeahead.js


Autocomplete or Live Search is nice functionality, because it has give us auto suggestion or recommendations, when we have start type in input field. If you have not know but Autocomplete feature has provide helps to User in different ways like auto search suggestion when we have search some specific product or some specific category. So when we have start type then it has provide suggestion which has fetch from database and display in autocomplete search suggestion dropdown list.

Under this Laravel 8 tutorial, we will implement Autocomplete Search by using Typeahead.js library. So this is Laravel 8 Autocomplete tutorial in which you can find how to add Autocomplete Search feature in Laravel 8 Application by using Typeahead JS with Mysql database.

If you want to make Autocomplete Search feature for your web application, then typeahead.js is the best solution. Typeahead.js is a Javascript library which helps us to make an outstanding Autocomplete Search functionality in our Laravel 8 Application.

Now we have proceed for create Autocomplete Search Module in our Laravel 8 application. In this tutorial, we will create model and migration and add fake data in Mysql database and from that data we will fetch and display in autocomplete search suggestion in our Laravel 8 application. So here we will build dynamic Autocomplete Search in Laravel 8 using Typeahead JS. For this you have to follow following steps.


Autocomplete Search in Laravel 8 using Typeahead.js

How to Implement Dynamic Autocomplete Search in Laravel using Typeahead.js


  1. Step 1 : Download & Install Laravel Framework
  2. Step 2 : Make Database Connection
  3. Step 3 : Create User Table in Database
  4. Step 4 : Generate Fake Records
  5. Step 5 : Create Controller
  6. Step 6 : Create index() method in Controller
  7. Step 7 : Create Blade View File
  8. Step 8 : Create action() method in Controller
  9. Step 9 : Set Routes for Controller Method
  10. Step 10 : Start Development Server
  11. Step 11 : Check Output in Browser

Step 1 : Download & Install Laravel Framework


For build Autocomplete search feature, first we want to install latest version of Laravel framework. For this we have go to command prompt and run following command.


composer create-project --prefer-dist laravel/laravel typeahead_autocomplete


This command will create typeahead_autocomplete directory and under that directory it will download latest version of Laravel framework. After download Laravel framework, then after we have go into typeahead_autocomplete this directory. For this we have to run following command in command prompt.


cd typeahead_autocomplete


Step 2 : Make Database Connection


In second step we have make Mysql Database connection with our Laravel 8 application. For this we have to open .env file and under this we have to define MySQL credential which you can seen below.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 : Create User Table in Database


In third step, we have to create User table in Mysql database. So when we have download latest version of Laravel framework then by default User.php model class and users table migration file will be available under this Laravel framework. So for create users we have to go command prompt and run following command. This command will create users table in MySQL database.


php artisan migrate

Step 4 : Generate Fake Records


Once if you have create users table then under this steps we have to insert fake records under this table. For this we have to open database/seeders/DatabaseSeeder.php file and under this file we have to write following code.

database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use App\Models\User;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();

        User::factory(100)->create();
    }
}
?>


After this we have open command prompt and run following command. This command will insert 100 fake data under this users table in MySQL Database.


php artisan db:seed --force


Step 5 : Create Controller


In fifth steps, we have to create controller class under Laravel framework. For this we have to open command prompt and fun following command.


php artisan make:controller TypeaheadAutocompleteController

This command will create TypeaheadAutocompleteController.php controller class file in app/Http/Controllers folder. Under this file first we want to import User models class. For this we have to write following code at header of this class file.


use App\Models\User;


Step 6 : Create index() method in Controller


After create controller class file, now in step six, we need to create index() method under this class. So this method will load typeahead_autocomplete.blade.php file in browser.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }
}
?>





Step 7 : Create Blade View File


In this step 7, we have need to create blade view file for display html output in browser. So here we have create typeahead_autocomplete.blade.php under resources/views directory. In the blade view, we need to import Typeahead js and bootstrap 4 library for make autocomplete in Laravel 8 app.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Typeahead JS Live Autocomplete Search in Laravel 8</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" ></script>
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">Typeahead JS Live Autocomplete Search in Laravel 8</h1>
            <br />
            <input type="text" name="user_name" id="user_name" class="form-control-lg" placeholder="Enter User Name..." />
        </div>
    </body>
</html>

<script>

var path = "{{ url('typeahead_autocomplete/action') }}";

$('#user_name').typeahead({

    source: function(query, process){

        return $.get(path, {query:query}, function(data){

            return process(data);

        });

    }

});

</script>


Step 8 : Create action() method in Controller


In steps 8, we have to crate action() method in Controller class file. Because this method will received ajax request from typeahead.js for fetch match data from database, and this method will send data to ajax request in JSON format.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }

    function action(Request $request)
    {
        $data = $request->all();

        $query = $data['query'];

        $filter_data = User::select('name')
                        ->where('name', 'LIKE', '%'.$query.'%')
                        ->get();

        return response()->json($filter_data);
    }
}



Step 9 : Set Routes for Controller Method


In steps 9, we need to set route for two method of controller class. For set route, we have to open routes/web.php file and under this file first we need to import TypeaheadAutocompleteController.php class file and then after write code for set route.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\TypeaheadAutocompleteController;

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

Route::get('/typeahead_autocomplete', [TypeaheadAutocompleteController::class, 'index']);

Route::get('/typeahead_autocomplete/action', [TypeaheadAutocompleteController::class, 'action'])->name('typeahead_autocomplete.action');


Step 10 : Start Development Server


Once we have follow all above step, so here our Laravel 8 application is ready with Autocomplete Search feature. So for check output in browser, first we have need to start Laravel development server. For this we have to open command prompt and run following command. This command will start server and provide us base url of our Laravel application.


php artisan serve


Step 11 : Check Output in Browser


After start development server, now we want to check output in browser. So in browser we have hit following url for check Autocomplete Search in Laravel 8 application.


http://localhost:8000/typeahead_autocomplete


Conclusion


So under this tutorial, we have seen how easily we can implement Typeahead.js Autocomplete search in Laravel 8 framework. So making this Autocomplete Search feature, we have seen that it is very useful in our web application, because when we have type something then this feature has provide us suggestion related to text which we have type in input field, and user can get filter suggestion and from that suggestion user can select option.

Monday, 5 July 2021

How to use Soft Delete to Restore Deleted Data in Laravel


In this Laravel tutorial we are going to learn How to use Soft Delete in Laravel framework. We will seen how can we restore deleted records and again we can see that records in our Laravel application with the help of soft delete.

So when we have use Soft Delete in our Laravel application so when we have delete data from our web application then that data is not deleted from database but that data we cannot see at our web application front-end side and at back-end side we can again recover and display or list in our application. So this things we will discuss under this tutorial by taking practical example how soft delete work in Laravel crud application.

How to Work Laravel Soft Delete


Suppose we have use Soft delete in Laravel web application, so when we have remove data from our application then that data is not actually removed from Mysql Database table. But current timestamp time has been updated at the deleted_at column. And when we have restore that deleted data then current timestamp value will be updated with nulled in deleted_at table column.

Please follow below step for how to implement soft delete in Laravel application for restore deleted records.


Preview


How to use Soft Delete to Restore Deleted Data in Laravel

Install Laravel Framework


For implement SoftDelete, first we need to download fresh copy of Laravel framework. So we have to go to command prompt and run following command.


composer create-project --prefer-dist laravel/laravel soft_delete


This command will first make soft_delete directory and under that directory it will download fresh copy of Laravel framework.




Make Database Connection


After download latest version of Laravel framework, first we need to make databae connection. So for make database connection in Laravel application, we have to open .env file and under that file we have to define our MySQL database configuration details.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Create Model Class


Once you have make database connection in Laravel framework, then in next step we have to create one model class and migration file for create table in MySQL database. So for this, we have to run following command in command prompt.


php artisan make:model Post -m


This command will make Post.php models class file in app/Models directory and migration file under database/migrations folder. First we have open migrations directory file and under that file, we have to define table column details which you can seen below.

database/migrations/2021_07_05_065844_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}



After this, we have to run following command in command prompt.


php artisan migrate

This command will run migration process and it will create posts table in your mysql database with following table column.


How to use Soft Delete to Restore Deleted Data in Laravel

Add SoftDelete in Models Class


Now in this steps we have to add Soft Delete in our Post.phpmodels class. But before we need create migrations for adding soft delete to posts table. So for this we have to run following command in command prompt.


php artisan make:migration add_sorft_delete_column


This above command will create new migration file at database/migrations directory which you can seen below.

database/migrations/new_migration_file.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddSorftDeleteColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function(Blueprint $table){
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function(Blueprint $table){
            $table->dropSoftDeletes();
        });
    }
}



After this we have to run migration command in command prompt.


php artisan migrate


Once you have run this command, then it will add deleted_at table column to posts table which you can seen below.


How to use Soft Delete to Restore Deleted Data in Laravel


Now for add dummy data, you have to run following sql script, so it will insert some dummy data in posts table.


INSERT INTO `posts` (`id`, `title`, `description`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Ajax Pagination using PHP with JavaScript', 'Ajax Pagination using PHP with JavaScript', '2021-07-02 07:27:03', '2021-07-05 01:17:26', NULL),
(2, 'Ajax Live Data Search using JavaScript with PHP', 'Ajax Live Data Search using JavaScript with PHP', '2021-07-02 07:27:03', '2021-07-05 01:17:26', NULL),
(3, 'Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js', 'Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js', '2021-07-02 07:27:03', '2021-07-03 06:35:02', NULL),
(4, 'How to Create Review & Rating Page in PHP with Ajax', 'How to Create Review & Rating Page in PHP with Ajax', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(5, 'Submit Form without Page Refresh using JavaScript with PHP', 'Submit Form without Page Refresh using JavaScript with PHP', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(6, 'How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP', 'How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(7, 'How to Export Data in Excel using Codeigniter 4', 'How to Export Data in Excel using Codeigniter 4', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(8, 'Laravel 8 Tutorial - Join Multiple Table using Eloquent Model	', 'Laravel 8 Tutorial - Join Multiple Table using Eloquent Model	', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(9, 'Toast Notification for Check Internet Connection with Bootstrap 4 & javascript	', 'Toast Notification for Check Internet Connection with Bootstrap 4 & javascript	', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(10, 'Dynamic Dependent Dropdown using Ajax in Codeigniter 4	', 'Dynamic Dependent Dropdown using Ajax in Codeigniter 4', '2021-07-02 07:27:04', '2021-07-02 07:27:04', NULL);


Next we want to add soft delete facade in our Post model, you can below find source code for add SoftDelete facade in Post models class.

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = ['title', 'description'];

    protected $dates = ['deleted_at'];
}





Create Controller Class


In next step, we have to create PostController and add following code in that controller file. So for create controller class file, we have need to run following command in command prompt.


php artisan make:controller PostController


This command will create PostController.php file at app/Http/Controllers directory. So need to open that file and add following code.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::get();

        if($request->has('view_deleted'))
        {
            $posts = Post::onlyTrashed()->get();
        }

        return view('post', compact('posts'));
    }

    public function delete($id)
    {
        Post::find($id)->delete();

        return back()->with('success', 'Post Deleted successfully');
    }

    public function restore($id)
    {
        Post::withTrashed()->find($id)->restore();

        return back()->with('success', 'Post Restore successfully');
    }

    public function restore_all()
    {
        Post::onlyTrashed()->restore();

        return back()->with('success', 'All Post Restored successfully');
    }
}



Under this controller class file we have make following method.

index(Request $request) : This method will fetch data on condition, suppose there is view_deleted variable has been received in url then it has only fetch deleted data otherwise it has fetch all data from database and send to view blade file.

delete($id) : This method has received request for delete data and it has received id in request, so based on value of that id it will perform soft delete operation.

restore($id) : This method has received get request for restore single data, so with restore request it has received id and that id data has been restore.

restore_all() : This method has received get request for restore all deleted data.

Create View Blade File


In Laravel framework for display output on browser we need to create blades file for display data on web page. In this example we have create blade file resources/views/post.blade.php directory.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>How to Use Soft Delete in Laravel</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">How to Use Soft Delete in Laravel</h1>
            <br />
            @if(session()->has('success'))

                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>

            @endif
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-md-6">Sample Data</div>
                        <div class="col col-md-6 text-right">
                            @if(request()->has('view_deleted'))

                            <a href="{{ route('post.index') }}" class="btn btn-info btn-sm">View All Post</a>

                            <a href="{{ route('post.restore_all') }}" class="btn btn-success btn-sm">Restore All</a>

                            @else

                            <a href="{{ route('post.index', ['view_deleted' => 'DeletedRecords']) }}" class="btn btn-primary btn-sm">View Deleted Post</a>

                            @endif
                            
                        </div>
                    </div>
                </div>
            
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            @if(count($posts) > 0)
                                @foreach($posts as $row)

                                <tr>
                                    <td>{{ $row->id }}</td>
                                    <td>{{ $row->title }}</td>
                                    <td>{{ $row->description }}</td>
                                    <td>
                                        @if(request()->has('view_deleted'))

                                            <a href="{{ route('post.restore', $row->id) }}" class="btn btn-success btn-sm">Restore</a>
                                        @else
                                            <form method="post" action="{{ route('post.delete', $row->id) }}">
                                                @csrf
                                                <input type="hidden" name="_method" value="DELETE" />
                                                <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                            </form>
                                        @endif
                                    </td>
                                </tr>

                                @endforeach
                            @else
                                <tr>
                                    <td colspan="4" class="text-center">No Post Found</td>
                                </tr>

                            @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>


Set Route


Under this step we need to set route for PostController.php class method. So for set file we need to open routes/web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

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


Route::get('post', [PostController::class, 'index'])->name('post.index');

Route::delete('post/{id}', [PostController::class, 'delete'])->name('post.delete');

Route::get('post/restore/one/{id}', [PostController::class, 'restore'])->name('post.restore');

Route::get('post/restore_all', [PostController::class, 'restore_all'])->name('post.restore_all');


Run Laravel Application


After follow all above step now we want to check Laravel application output. So first we have run server. So for this we have to run following command in command prompt.


php artisan serve

This command will star server and provide us base url of our Laravel application. So for check output of above code, we have to hit following url in browser.


http://127.0.0.1:8000/post


So this are the complete process for how to use SoftDelete in Laravel and implement Restore Deleted Records feature in your Laravel application. We hope this tutorial will help you to learn something new in Laravel framework.

Download Complete Source Code


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.