Laravel 8 ConsoleTvs Charts Tutorial

how to use consoletvs charts in laravel 8
Hi Guys, Today,I will learn you how to use consoletvs charts in laravel 8. If you need to add some graphs to your views, maybe you have work with some js library to add cool graphics but even with a good library like ChartJS implementing this is not so easy. Step 1: Install Laravel 8 Application we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2 :Installing consoletvs Package Now In this step, install consoletvs/charts:6 package in laravel 8 app via following command.
composer require consoletvs/charts:6
If you are working with Laravel 5.5 or higher thats all you need to install the package thanks by autodiscover feature. If you work with Laravel lower than 5.5 you will need to register a service provider, add this line into the config/app.php file in the providers section:
ConsoleTVs\Charts\ChartsServiceProvider::class,
And to publish the configuration in terminal with the command:
php artisan vendor:publish --tag=charts_config
Now you have the package installation done! Step 3: Use the package in this step, We are going to use artisan cli to create a chart class.
php artisan make:chart UserChart
Now in app directory we can see a folder named charts and there is our new class UserChart.php. Step 4: Create Controller I will explain with an easy example but you can add as many complexity as you want, we are going to create a controller of type resource to display user chart:
php artisan make:controller UserChartController -r
Now you can edit the file in app/Http/Controllers/UserChartController.php and only hold the index method all other rest full methods can be deleted, and you will have something like this:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

}
To make it more easy I will create a fake data but you can use eloquent o queryBuilder to create queries as you need, I will import the new chart class created before to the controller, and start to create a chart with Laravel chart api fluid syntax:
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13]);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}
Now we need a view to show the data in the last code snippet the index method returns a view for users charts, so I will create a file in resources/views/ named users.blade.php, with next content:
@extends('layouts.app')

@section('content')
<h1>Sales Graphs</h1>

<div style="width: 50%">
    {!! $salesChart->container() !!}
</div>
@endsection
Now we pass the chart script to the view file we only need to add the chart css and js library files, to keep it simple we are going to use the layout app blade file, it is located in resources/views/layout/app.blade.php, here we are going to add in header section the next line at the very bottom:
<head>
    <meta charset="utf-8">
    ...
    {{-- ChartScript --}}
    @if($usersChart)
    {!! $usersChart->script() !!}
    @endif
</head>
To add JS library file we are going to the bottom to the file app.blade.php, before the html close tag and add the scripts:
@extends('layouts.app')

@section('content')
<h1>Users Graphs</h1>

<div style="width: 50%">
    {!! $usersChart->container() !!}
</div>
@endsection
Finally we only need a route to access to the graphic view, in routes/web.php file you can add a route with get method to access to the usersChartController class in method index() in the example I set a route to 'sales':
<?php
use App\Http\Controllers\UserChartController;
/*
|--------------------------------------------------------------------------
| 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('users', 'UserChartController@index');
Well it is simple but, maybe you want to customize it a little bit more, you can customize the charts by two ways, you can customize the "dataset" and the chart as itself, to start we are going to customize the "dataset":
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13])
            ->color("rgb(255, 99, 132)")
            ->backgroundcolor("rgb(255, 99, 132)");
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}
The method "color" set the border color in the case of a "line" or "area" charts it sets the line color, and as param requires a string with the rgb or rgba color The method "backgroundcolor" set the area color, the color to fill, and as param requires a string with the rgb or rgba color
"fill" method requires a boolean and it paint the area or not if it is set as false, by default a chart is filled.
"linetension" method make less curved a line and it requires a float from 0.0 to 1.0
"dashed" method makes the line a dashed line and it requires an array.

Customize the chart

To customize the chart we can use some methods: ->"minimalist" method requires a boolean and it removes the grid background and the legend of the chart ->"displaylegend" methods requires a boolean and it is true by default, to hide the legend set false as param. ->"displayaxes" method requieres a boolean and by default is true it, paint the background grid of the chart, to hide it just set false as the param. ->"barWidth" this method does not do anything in line and area charts, it requires a double.
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->title('Users by Months', 30, "rgb(255, 99, 132)", true, 'Helvetica Neue');
        $usersChart->barwidth(0.0);
        $usersChart->displaylegend(false);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13])
            ->color("rgb(255, 99, 132)")
            ->backgroundcolor("rgb(255, 99, 132)")
            ->fill(false)
            ->linetension(0.1)
            ->dashed([5]);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Doughnutexample:

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $borderColors = [
            "rgba(255, 99, 132, 1.0)",
            "rgba(22,160,133, 1.0)",
            "rgba(255, 205, 86, 1.0)",
            "rgba(51,105,232, 1.0)",
            "rgba(244,67,54, 1.0)",
            "rgba(34,198,246, 1.0)",
            "rgba(153, 102, 255, 1.0)",
            "rgba(255, 159, 64, 1.0)",
            "rgba(233,30,99, 1.0)",
            "rgba(205,220,57, 1.0)"
        ];
        $fillColors = [
            "rgba(255, 99, 132, 0.2)",
            "rgba(22,160,133, 0.2)",
            "rgba(255, 205, 86, 0.2)",
            "rgba(51,105,232, 0.2)",
            "rgba(244,67,54, 0.2)",
            "rgba(34,198,246, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
            "rgba(233,30,99, 0.2)",
            "rgba(205,220,57, 0.2)"

        ];
        $usersChart = new UserChart;
        $usersChart->minimalist(true);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'doughnut', [10, 25, 13])
            ->color($borderColors)
            ->backgroundcolor($fillColors);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Bar example

With a little effort and the default bootstrap from Laravel installation: UserChartController to generate the chart
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $borderColors = [
            "rgba(255, 99, 132, 1.0)",
            "rgba(22,160,133, 1.0)",
            "rgba(255, 205, 86, 1.0)",
            "rgba(51,105,232, 1.0)",
            "rgba(244,67,54, 1.0)",
            "rgba(34,198,246, 1.0)",
            "rgba(153, 102, 255, 1.0)",
            "rgba(255, 159, 64, 1.0)",
            "rgba(233,30,99, 1.0)",
            "rgba(205,220,57, 1.0)"
        ];
        $fillColors = [
            "rgba(255, 99, 132, 0.2)",
            "rgba(22,160,133, 0.2)",
            "rgba(255, 205, 86, 0.2)",
            "rgba(51,105,232, 0.2)",
            "rgba(244,67,54, 0.2)",
            "rgba(34,198,246, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
            "rgba(233,30,99, 0.2)",
            "rgba(205,220,57, 0.2)"

        ];
        $usersChart = new UserChart;
        $usersChart->minimalist(true);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'bar', [10, 25, 13])
            ->color($borderColors)
            ->backgroundcolor($fillColors);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}
blade view with some bootstrap for styling
@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Users Graphs</h1>
    <div class="row">
        <div class="col-6">
            <div class="card rounded">
                <div class="card-body py-3 px-3">
                    {!! $usersChart->container() !!}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
It will help you...

Laravel 8 Resize Image Before Upload Example Tutorial

laravel 8 generate thumbnail image

Hi Guys,

Today, I will learn you how to resize image before upload in laravel 8. we will show example of resize image before upload in laravel 8.if you want to see example of laravel 8 generate thumbnail image then you are a right place. we will help you to give example of laravel 8 resize image before upload.I will explain step by step tutorial laravel 8 resize image.

We will give you simple example of laravel 8 image intervention example. you will do the following things for resize and upload image in laravel 8.

we will use intervention/image package for resize or resize image in laravel. intervention provide a resize function that will take a three parameters. three parameters are width, height and callback function. callback function is a optional.

Here, I will give you full example for simply resize image before upload using laravel as bellow.

Step 1: Install Laravel 8

Here In this step, If you haven't laravel 8 application setup then we have to get fresh laravel 8 application. So run bellow command and get clean fresh laravel 8 application.

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Intervention Image Package

n this step,I will install intervention/image for resize image. this package through we can generate thumbnail image for our project. so first fire bellow command in your cmd or terminal.

composer require intervention/image

Now we need to add provider path and alias path in config/app.php file so open that file and add bellow code.

config/app.php
return [
    ......
    $provides => [
        ......,
        ......,
        Intervention\Image\ImageServiceProvider::class
    ],
    $aliases => [
        ......,
        .....,
        'Image' => Intervention\Image\Facades\Image::class
    ]
]
Step 3: Create Routes

In this step,we will add routes and controller file so first add bellow route in your routes.php file.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageResizeController;
  
/*
|--------------------------------------------------------------------------
| 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('resizeImage', [ImageResizeController::class, 'resizeImage']);
Route::post('resizeImagePost', [ImageResizeController::class, 'resizeImagePost'])->name('resizeImagePost');
Step 4: Create Controller File

In this step,Now require to create new ImageResizeController for image uploading and resizeing image so first run bellow command.

php artisan make:controller ImageResizeController

After this command you can find ImageResizeController.php file in your app/Http/Controllers directory. open ImageResizeController.php file and put bellow code in that file.

app/Http/Controllers/ImageResizeController.php
<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Http\Requests;
use Image;
  
class ImageResizeController extends Controller
{
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function resizeImage()
    {
        return view('resizeImage');
    }
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function resizeImagePost(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $image = $request->file('image');
        $input['imagename'] = time().'.'.$image->extension();
     
        $destinationPath = public_path('/thumbnail');
        $img = Image::make($image->path());
        $img->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPath.'/'.$input['imagename']);
   
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $input['imagename']);
   
        return back()
            ->with('success','Image Upload successful')
            ->with('imageName',$input['imagename']);
    }
   
}
Step 5: View File and Create Upload directory

In this last step we will create resizeImage.blade.php file for photo upload form and manage error message and also success message. So first create resizeImage.blade.php file and put bellow code:

resources/views/resizeImage.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Resize Image Tutorial</title>
    <link rel="stylesheet" href="https://www.nicesnippets.com/adminTheme/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
  
<div class="container">
    <h1>Laravel Resize Image Tutorial</h1>
    @if (count($errors) > 0)
        <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
         
    @if ($message = Session::get('success'))
    <div class="alert alert-success alert-block">
        <button type="button" class="close" data-dismiss="alert">×</button>    
        <strong>{{ $message }}</strong>
    </div>
    <div class="row">
        <div class="col-md-4">
            <strong>Original Image:</strong>
            <br/>
            <img src="/images/{{ Session::get('imageName') }}" />
        </div>
        <div class="col-md-4">
            <strong>Thumbnail Image:</strong>
            <br/>
            <img src="/thumbnail/{{ Session::get('imageName') }}" />
        </div>
    </div>
    @endif
         
    <form action="{{ route('resizeImagePost') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="row">
            <div class="col-md-4">
                <br/>
                <input type="text" name="title" class="form-control" placeholder="Add Title">
            </div>
            <div class="col-md-12">
                <br/>
                <input type="file" name="image" class="image">
            </div>
            <div class="col-md-12">
                <br/>
                <button type="submit" class="btn btn-success">Upload Image</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>
Now at last create two directory in your public folder (1)images and (2)thumbnail and please give permission to that folder and check....at last create two directory in your public folder (1)images and (2)thumbnail and please give permission to that folder and check.... It will help you...

Laravel Custom ENV Variables Tutorial

Hi Dev,

Today,I will learn you how to add custom env variables in laravel. We will example of laravel custom env variables. i explained simply about how to add custom env variables in laravel. i would like to share with you add new custom env variables laravel. Let's get started with laravel create new env variable.

we may require to add new env variable and use it. i will give you two examples of how to adding new env variable and how to use it with laravel application.

Here, I will give you full example for simply custom env variables using laravel as bellow.

Example 1: using env() helper

In this example,first add your new variable on env file as like bellow.

.env
...
  
GOOGLE_API_TOKEN=xxxxxxxx
Use it.
Route::get('helper', function(){
    $googleAPIToken = env('GOOGLE_API_TOKEN');
      
    dd($googleAPIToken);
  
});
Output:
xxxxxxxx
Example 2: using config() helper

In this example,now first add your new variable on env file as like bellow.

.env
...
GOOGLE_API_TOKEN=xxxxxxxx
config/google.php
<?php
  
return [
    'api_token' => env('GOOGLE_API_TOKEN', 'your-some-default-value'),
];
  
Use it:
Route::get('helper', function(){
    $googleAPIToken = config('google.api_token');
      
    dd($googleAPIToken);
  
});
Output:
xxxxxxxx

It will help you....

Jquery UI Nested Tabs Tutorial

jquery ui tabs with subtabs

Hi guys

This post will give you example of jquery ui nested tabs example . Here you will learn jquery ui sub tabs example. This tutorial will give you simple example of example of jquery ui tabs with subtabs. This tutorial will give you simple example of jquery ui tabs with subtabs.

In this blog, I will explain how to create nested tabs in jquery ui.we will show example of jquery ui nested tabs.I will jquery ui using create nested tabs.tabs view In other tab view create using jquery ui.We will make sub tabs using jquery and jqueryUi.I will show easy example of jquery ui sub tabs.

Here the example of jquery ui nested tabs.

Example

Now this nested tabs html design code:

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery UI Nested Tabs Example</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
    <script data-require="jquery@2.1.1" data-semver="2.1.1" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script data-require="jquery-ui@1.10.4" data-semver="1.10.4" src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
<style type="text/css">
  .fix {
    background: green;
    background: rgba(0,255,0,0.3);
  }
  .broken {
    background: red;
    background: rgba(255,0,0,0.3);
  }
</style>
  <body>
    <p>
      Tabs below is working how we expect it. It opens tab2 and subtab2 on a pageload.
    </p>
    <div class="tabs fix">
      <ul>
        <li>
          <a href="#tabs-1">Tab 1</a>
        </li>
        <li>
          <a href="#tabs-2">Tab 2</a>
        </li>
        <li>
          <a href="#tabs-3">Tab 3</a>
        </li>
      </ul>
      <div class="tabContainer">
        <div id="tabs-1" class="tabContent">
          <p>Some content 1.</p>
        </div>
        <div id="tabs-2" class="tabContent">
          <div class="subtabs">
            <ul>
              <li><a href="#subtab1">Subtab1</a></li>
              <li><a href="#subtab2">Subtab2</a></li>
            </ul>
            <div id="subtab1" class="subtabContent">
             Some sub content1 
            </div>
            <div id="subtab2" class="subtabContent">
             Some sub content2
            </div>
          </div>
        </div>
        <div id="tabs-3" class="tabContent">
          <p>Some content 3</p>
        </div>
      </div>
    </div>
  </body>
</html>
blow the nested tabs of jqueryui script code add:

<script type="text/javascript">
  // Code goes here
$(document).ready(function() {
  jQuery( ".tabs" ).tabs();
  jQuery( ".subtabs" ).tabs();
  
  openParentTab();
});
function openParentTab() {
  locationHash = location.hash.substring( 1 );
  console.log(locationHash);
  // Check if we have an location Hash
  if (locationHash) {
    // Check if the location hash exsist.
    var hash = jQuery('#'+locationHash);
    if (hash.length) {
      // Check of the location Hash is inside a tab.
      if (hash.closest(".tabContent").length) {
        // Grab the index number of the parent tab so we can activate it
        var tabNumber = hash.closest(".tabContent").index();
        jQuery(".tabs.fix").tabs({ active: tabNumber });
        // Not need but this puts the focus on the selected hash
        hash.get(0).scrollIntoView();
        setTimeout(function() {
          hash.get(0).scrollIntoView();
        }, 1000);
      }
    }
  }
}
</script>

It will help you...

Laravel 8 Autocomplete Search using Typeahead JS Example

 autocomplete search using typeahead

Hi Guys,

Today,I will learn you how to create autocomplete search using typeahead js in laravel 8. We will show example of laravel 8 autocomplete search using typeahead js. We will share with you how to build search autocomplete box using jQuery typehead js with ajax in laravel 8.i will use jQuery typehead js plugin, bootstrap library and ajax to search autocomplete in laravel 8 app.

Here, I will give you full example for Laravel 8 ajax autocomplete search using typeahead js as bellow.

Step 1: Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel Laravel8TypeheadTutorial
Step 2: Database Configuration

In this step, configure database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Step 3: Add Dummy Record

In this step,I will Generate dummy records into database table users. So, navigate database/seeders/ directory and open DatabaseSeeder.php file. Then add the following two line of code it.

use App\Models\User;

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

After that, open command prompt and navigate to your project by using the following command:

  cd / Laravel8TypeheadTutorial

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Next, run the following database seeder command to generate dummy data into database:

php artisan db:seed --force
Step 4: Create Routes

Now in this step, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\AutocompleteSearchController;
Route::get('/autocomplete-search', [AutocompleteSearchController::class, 'index'])->name('autocomplete.search.index');
Route::get('/autocomplete-search-query', [AutocompleteSearchController::class, 'query'])->name('autocomplete.search.query');
Step 5: Creating Auto Complete Search Controller

Here in this step,I will create search AutocompleteSearch controller by using the following command.

php artisan make:controller AutocompleteSearchController

The above command will create AutocompleteSearchController.php file, which is located inside

Laravel8TypeheadTutorial/app/Http/Controllers/ directory.

Then add the following controller methods into AutocompleteSearchController.blade.php file:

<?php

namespace App\Http\Controllers;

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

class AutocompleteSearchController extends Controller
{
    public function index()
    {
      return view('autocompleteSearch');
    }

    public function query(Request $request)
    {
      $input = $request->all();

        $data = User::select("name")
                  ->where("name","LIKE","%{$input['query']}%")
                  ->get();
   
        return response()->json($data);
    }
}
Step 6: Create Blade File

In step 6, create new blade view file that named autocompleteSearch.blade.php inside resources/views directory for ajax get data from database.

<!DOCTYPE html>
<html>
<head>
  <title>Autocomplete Search Using Typehead | Laravel 8</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3 mt-5">
        <h5>Laravel 8 Autocomplete Search Using Typehead</h5>
        <input type="text" class="form-control typeahead">
      </div>
    </div>
  </div>
</body>
<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>
<script type="text/javascript">
  var path = "{{ url('autocomplete-search-query') }}";
    $('input.typeahead').typeahead({
        source:  function (query, process) {
          return $.get(path, { query: query }, function (data) {
              return process(data);
          });
        }
    });
</script>
</html>

Now we are ready to run our laravel 8 autocomplete search using typeahead js example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/autocomplete-search

It will help you..

Laravel Validation Number Less Than Example

Hi Guys,

Today, I will learn you to create validation lt in laravel.we will show example of laravel validation lt.The given field The field under validation must be less than the given field. The two fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions as the size rule.

Here, I will give you full example for simply lt validation in laravel bellow.

solution
$request->validate([
  'detail' => 'lt:20',
]);
Route : routes/web.php
Route::get('form/create','FromController@index');
Route::post('form/store','FromController@store')->name('form.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
          'detail' => 'lt:20',
        ]);
      dd('done');
    }
}
View : resources/views/form.blade.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
              
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
                @if (count($errors) > 0)
                      <div class="row">
                          <div class="col-md-12">
                              <div class="alert alert-danger alert-dismissible">
                                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                                  @foreach($errors->all() as $error)
                                  {{ $error }} <br>
                                  @endforeach      
                              </div>
                          </div>
                      </div>
                    @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Password:</label>
                      <input name="password" type="password" class="form-control" placeholder="Enter password">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Vue Js Toggle Switch Button Example

Hi Dev,

In this example, I will explain you how to use toggle switch button in vue js. wr will show example of toggle switch button in vue js.we will use vue-js-toggle-button npm package for bootstrap toggle button example. vue cli toggle button is a simple, pretty and customizable.

vue-js-toggle-button provide way to change label and make it default checked. you can also customize several option like value, sync, speed, color, disabled, cssColor, labels, switchColor, width, height, name and with change event.

below i will give you simple example from starch so, you can see full example use it in your app.

Step 1: Create Vue JS App

Now this step, we need to create vue cli app using bellow command:

vue create myAppSwitch
Step 2: Install vue-js-toggle-button package

below we need to install vue-js-toggle-button npm package for toggle switch.

npm install vue-js-toggle-button --save
Step 3: Use vue-js-toggle-button

In this step, We need to use vue-js-toggle-button package in main.js file of vue js app.

src/main.js
import Vue from 'vue'
import App from './App.vue'
import ToggleButton from 'vue-js-toggle-button'
  
Vue.config.productionTip = false
Vue.use(ToggleButton)
  
new Vue({
  render: h => h(App),
}).$mount('#app')
Step 4: Update App.vue File

Now this step, we need to update app.vue file, because i updated component so.

src/App.vue
<template>
  <div id="app">
    <Example></Example>
  </div>
</template>
  
<script>
import Example from './components/Example.vue'
   
export default {
  name: 'app',
  components: {
    Example
  }
}
</script>
Step 5: Create Example Component

Here, we will create Example.vue component with following

code. src/components/Example.vue
<template>
  <div class="container" style="text-align:center">
    <div class="large-12 medium-12 small-12 cell">
      <h1 style="font-family:ubuntu">Vue js toggle button example - Nicesnippets.com</h1>
  
        <toggle-button @change="onChangeEventHandler" :labels="{checked: 'On', unchecked: 'Off'}" style="margin-left: 20px" />
  
        <toggle-button :labels="{checked: 'Itsolutionstuff.com', unchecked: 'HDTuto.com'}" width="150" style="margin-left: 20px" />
  
        <toggle-button :labels="{checked: 'Yes', unchecked: 'No'}" style="margin-left: 20px" />
  
    </div>
  </div>
</template>
  
<script>
    
  export default {
    data(){
      return {
        file: ''
      }
    },
  
    methods: {
      onChangeEventHandler(){
          alert('hi');
      }
    }
  }
</script>

Now you can run vue app by using following command:

npm run serve

It will help you....

Laravel Validation Image Example

example for simply image validation in laravel

Hi Guys,

Today, I will learn you to create validation image in laravel.we will show example of laravel validation image.The file under validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).

Here, I will give you full example for simply image validation in laravel bellow.

solution
$request->validate([
   'file' => 'image'
]);
Route : routes/web.php
Route::get('form/create','FromController@index');
Route::post('form/store','FromController@store')->name('form.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
           'file' => 'image'
        ]);
      dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <scrbooleant src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scrbooleant>
  <scrbooleant src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scrbooleant>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                Laravel Validation Image Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
                  <div class="row">
                      <div class="col-md-12">
                          <div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                              @foreach($errors->all() as $error)
                              {{ $error }} <br>
                              @endforeach      
                          </div>
                      </div>
                  </div>
                @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Image:</label>
                      <input name="file" type="file" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Laravel Convert PDF to Image Example

convert pdf to image laravel

Hi Guys,

Today,I will learn you how to convert pdf to image in laravel. we will Pdf To Image Convert using imagick package. you can easyliy convert pdf to image any formate in laravel. if you want to convert pdf to image than you can use here example. we will show setp by step example laravel pdf to image convert.

Here, I will give you full example for pdf to image convert in laravel as below.

Step 1: Install Laravel

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Step 2: Installing Imagick PHP Extension And Configuration

Here In this step, I will install the Imagick PHP extension is available from the Ubuntu’s repositories. Like ImageMagick, to do an imagick php install we can simply run the apt install command.

sudo apt install php-imagick

If you require a previous version of php-imagick, you can list the version available from the Ubuntu repositories using the apt list command. This would be useful in the event that the latest patch introduces regressions, which is fairly uncommon.

sudo apt list php-magick -a

The -a flag tells apt to list all version of a package available from the repositories. The output will look similar to the following, and at the time of this writing, there was only a single version available.

php-imagick/bionic,now 3.4.3~rc2-2ubuntu4 amd64 [installed]
restart apache web server

Installing the module alone isn’t enough. In order for any new PHP extension to be used with your web application Apache must be restarted.

sudo systemctl restart apache2
Verify Installation

To verify the installation was successful and that the module is enabled properly, we can use php -m from the command line, and grep the results to limit the output to only the line that is important.

Run the following command to verify the installation.

 php -m | grep imagick

If the installation was successful, the output of the command will simply show one line, and it will only contain the name of the module imagick.

imagick

For a much more detailed verification of whether the PHP module was installed correctly, use the phpinfo() method.

From the command line, run the following command

php -r 'phpinfo();' | grep imagick

Which will output the following information, where the modules status is shown as enabled.

/etc/php/7.3/cli/conf.d/20-imagick.ini,
imagick
imagick module => enabled
imagick module version => 3.4.4
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel
imagick.locale_fix => 0 => 0
imagick.progress_monitor => 0 => 0
imagick.set_single_thread => 1 => 1
imagick.shutdown_sleep_count => 10 => 10
imagick.skip_version_check => 1 => 1

Alternatively, by adding the phpinfo() function to a php script, and then accessing the script from a web browser, we are able to see the module is installed and enabled.

After some authorization change in fowling the path

/etc/ImageMagick-6/policy.xml
 < policy domain="coder" rights="none" pattern="PDF" / >
To Convert
 < policy domain="coder" rights="read|write" pattern="PDF" / >
Step 3: Create Route

Now, we need to add resource route for pdf to image convert in laravel application. so open your "routes/web.php" file and add following route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FromController;

Route::get('form', [FromController::class, 'index'])->name('form');
Step 3: Create Controller here this step now we should create new controller as FromController,So run bellow command for generate new controller
php artisan make:controller FromController
At last step we need to update FromController.php.
<?php

namespace App\Http\Controllers;

use Imagick;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $imagick = new Imagick();

        $imagick->readImage(public_path('dummy.pdf'));

        $imagick->writeImages('converted.jpg', true);

        dd("done");
    }
}

Now we are ready to run our custom validation rules example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/form

It will help you....

Laravel Validation Accepted Example

Hi Guys,

Today, I will learn you to create validation accepted in laravel.we will show example of laravel validation accepted.The field under validation must be "yes", "on", 1, or true. This is useful for validating "Terms of Service" acceptance or similar fields.

Here, I will give you full example for simply accepted validation in laravel bellow.

solution
$request->validate([
  'terms' => 'accepted',
]);
Route : routes/web.php
Route::get('form/create','FromController@index');
Route::post('form/store','FromController@store')->name('form.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
          'terms' => 'accepted',
        ]);

        dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                Laravel Accepted Validation Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
                @if (count($errors) > 0)
                  <div class="row">
                      <div class="col-md-12">
                          <div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                              @foreach($errors->all() as $error)
                              {{ $error }} <br>
                              @endforeach      
                          </div>
                      </div>
                  </div>
                @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label><input name="terms" type="checkbox" class=""> Terms of Service</label>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Laravel Validation Required Example

Hi Guys,

Today, I will learn you to create validation required in laravel.we will show example of laravel validation required. The field under validation must be present in the input data and not empty. A field is considered "empty" if one of the following conditions are true

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

Here, I will give you full example for simply required validation in laravel bellow.

solution
$request->validate([
  'rank' => 'required',
]);
Route : routes/web.php
Route::get('form/create','FromController@index');
Route::post('form/store','FromController@store')->name('form.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
            'rank' => 'required',
        ]);
      dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation numeric Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
                @if (count($errors) > 0)
                      <div class="row">
                          <div class="col-md-12">
                              <div class="alert alert-danger alert-dismissible">
                                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                                  @foreach($errors->all() as $error)
                                  {{ $error }} <br>
                                  @endforeach      
                              </div>
                          </div>
                      </div>
                    @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Rank:</label>
                      <input name="rank" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Codeigniter For Validation With Error Message Example

Hi Guys

In this tutorial,i will show you how to implement server side validation example,it can easyli Codeigniter Server Side Form Validation With Error Message in this example,normal validation two sides like server side and client side, i will give you simple example of form validation in codeigniter application. we will use form_validation library for add form validation with error message display in codeigniter.

we can use defaulut following validation rules of codeigniter.We can use default following validation rules of codeigniter

  • required
  • regex_match
  • matches
  • differs
  • is_unique
  • min_length
  • max_length
  • exact_length
  • greater_than
  • You can see more from here
Codeigniter Validation Rules. Exmaple

So here i gave you full example of form validation in codeigniter application. i created simple form with first name, last name, email and Mobile Number like contact us form and i set server side validation.

Step:1 Download Codeigniter Project

Here in this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ . And change the download folder name "demo"

Step:2 Basic Configurations

Here in this step,we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';
Step:3 Create Database With Table

Here in this step,we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo. you can use the below sql query for creating a table in your database.

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    first_name varchar(100) NOT NULL COMMENT 'Name',
    last_name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
Step:4 Setup Database Credentials

Here in this step,we need in this step connect our project to database. go to the application/config/ and open database.php file in text editor.We need to setup database credential in this file like below.

$db['default'] = array(
  'dsn' => '',
  'hostname' => 'localhost',
  'username' => 'root',
  'password' => '',
  'database' => 'demo',
  'dbdriver' => 'mysqli',
  'dbprefix' => '',
  'pconnect' => FALSE,
  'db_debug' => (ENVIRONMENT !== 'production'),
  'cache_on' => FALSE,
  'cachedir' => '',
  'char_set' => 'utf8',
  'dbcollat' => 'utf8_general_ci',
  'swap_pre' => '',
  'encrypt' => FALSE,
  'compress' => FALSE,
  'stricton' => FALSE,
  'failover' => array(),
  'save_queries' => TRUE
);
Step:5 Create Controller

Here in this step,we create a controller name Users.php. In this controller we will create some method/function. We will build some of the methods like :

-> Index() – This is used to display a form.

-> post_validate() – This is used to validate data on server side and store a data into database.

<?php
class Users extends CI_Controller {
  
    public function __construct()
    {
        parent::__construct();
        $this->load->library(array('form_validation','session'));
        $this->load->helper(array('url','html','form'));
        $this->load->database();
    }
  
    public function index()
    {
      $this->load->view('form_validation');
    }
    public function post_validate()
    {
 
        $this->form_validation->set_rules('first_name', 'First Name', 'required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'required');
        $this->form_validation->set_rules('contact_no', 'Contact No', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');
 
        $this->form_validation->set_error_delimiters('<div class="error">','</div>');
        $this->form_validation->set_message('required', 'Enter %s');
 
        if ($this->form_validation->run() === FALSE)
        {  
            $this->load->view('form_validation');
        }
        else
        {   
          $data = array(
             'first_name' => $this->input->post('first_name'),
             'last_name' => $this->input->post('last_name'),
             'contact_no' => $this->input->post('contact_no'),
             'email' => $this->input->post('email'),
 
           );
   
            $insert = $this->db->insert('users', $data);
            if ($insert) {
               $this->load->view('success');
            } else {
               redirect( base_url('users') ); 
            }
   
            }
 
    }
 
}
Step:6 Create Views

Now in this step we will create a form_validation.php , go to application/views/ folder and create form_validation.php file. Here put the below html code for showing form.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Form Validation - nicesnippets.com </title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
 <div class="container">
    <br>
    <div class="row">
    <div class="col-md-9">
    <form action="<?php echo base_url('users/post_validate') ?>" method="post" accept-charset="utf-8">
      <div class="form-group">
        <label for="formGroupExampleInput">First Name</label>
        <input type="text" name="first_name" class="form-control" id="formGroupExampleInput" placeholder="Please enter first name">
        <?php echo form_error('first_name'); ?> 
      </div> 
 
      <div class="form-group">
        <label for="formGroupExampleInput">Last Name</label>
        <input type="text" name="last_name" class="form-control" id="formGroupExampleInput" placeholder="Please enter last name">
        <?php echo form_error('last_name'); ?>  
      </div>
 
      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
        <?php echo form_error('email'); ?> 
      </div>   
 
      <div class="form-group">
        <label for="mobile_number">Mobile Number</label>
        <input type="text" name="contact_no" class="form-control" id="contact_no" placeholder="Please enter mobile number" maxlength="10">
        <?php echo form_error('contact_no'); ?> 
      </div>
 
      <div class="form-group">
       <button type="submit" id="send_form" class="btn btn-success">Submit</button>
      </div>
    </form>
    </div>
    <div class="col-md-3">
      <?php $this->load->view('layout/media_left_side_bar'); ?>
    </div>
    </div>
</div>
</body>
</html>
Step:7 Success Views

Now in this step we need to create success.php file, so go to application/views/ and create success.php file. And put the below code here.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Form Validation - nicesnippets.com </title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
 <h1> Thank You for Registered</h1>
</div>
</body>
</html>
Start Server And Run Program

For start development server, Go to the browser and hit below the url.

http://localhost/demo/users

I hope it can help you...

PHP Ajax Image Upload With Preview Example

Hi Guys,

In this tutorial, i will give you simple example of ajax image upload with preview in php. Uploading image via an jquery AJAX in php. I have added code for doing PHP image upload with AJAX without reloading the page.

xI use jQuery AJAX to implement image upload. There is a form with file input field and a submit button. On submitting the form with the selected image file, the AJAX script will be executed. In this code, it sends the upload request to PHP with the uploaded image. PHP code moves the uploaded image to the target folder and returns the image HTML to show the preview as an AJAX response.

The following code shows the HTML for the image upload form. On submitting this form the AJAX function will be called to send the request to the PHP image upload code.

Create Form form.php
<html>
<head>
   <title>PHP AJAX Image Upload</title>
   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">
</head>
<body>
<div class="container">
   <div class="col-md-6 offset-md-3">
      <div class="card">
         <div class="card-title p-1 bg-success">
            <h6>PHP AJAX Image Upload</h6>
         </div>
         <div class="card-body">
            <form id="uploadForm" action="upload.php" method="post">
               <div class="col-md-12 bg-light mb-2 text-center">
                  <div id="targetLayer">No Image</div>
               </div>
               <div class="form-group">
                  <input name="userImage" type="file" class="form-controller" />
               </div>
               <input type="submit" value="Submit" class="btn btn-success" />
            </form>
         </div>
      </div>
   </div>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function (e) {
   $("#uploadForm").on('submit',(function(e) {
      e.preventDefault();
      $.ajax({
           url: "upload.php",
         type: "POST",
         data:  new FormData(this),
         contentType: false,
         cache: false,
         processData:false,
         success: function(data)
          {
            $("#targetLayer").html(data);
          },
              error: function() 
          {
          }            
      });
	}));
});
</script>
</html>
Create Upload Fille upload.php
<?php
  if(is_array($_FILES)) {
    if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
      $sourcePath = $_FILES['userImage']['tmp_name'];
      $targetPath = "images/".$_FILES['userImage']['name'];
      if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img class="img-fluid" width="100%" height="100" src="<?php echo $targetPath; ?>" />
<?php
  }
    }
      }
?>

it code is a redy php ajax image upload with preview and the run code.

it will help you..

Laravel Livewire Fullcalendar Integration Example

Hi Guys,

Today, I will learn you how to use fullcalendar with livewire example. We will explain step-by-step laravel livewire fullcalendar integration. you can easily make livewire fullcalendar integration in laravel. we will describe laravel livewire fullcalendar integration.

Here, I will give you full example for simply livewire fullcalendar integration in laravel native as bellow.

Step 1 : Install Laravel App

In First step, We need to get fresh laravel version application using bellow command. So Let's open terminal and run bellow command.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Step 3 : Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire
Step 4 : Create items Table and Model

In this step we have to create migration for items table using Laravel php artisan command, so first fire bellow command:

php artisan make:model Event -m

After this command you have to put bellow code in your migration file for create items table.

following path: /database/migrations/2021_04_10_102325_create_events_table.php
<?php

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

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

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

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create items table.

following path:/app/Models/Event.php
<?php

namespace App\Models;

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

class Event extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'start',
    ];
}
Step:5 Create Route

In thi step,now, we need to add resource route for livewire fullcalendar integration in application. so open your "routes/web.php" file and add following route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Livewire\Calendar;
use App\Models\Event;
/*
|--------------------------------------------------------------------------
| 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::view('/', 'home');

Livewire::component('calendar', Calendar::class);
Step 6 : Create Component

Now, You can create livewire component using bellow command, So Let's run bellow command to create calendar form component:

php artisan make:livewire calendar
Now they created fies on both path:
app/Http/Livewire/Calendar.php
resources/views/livewire/calendar.blade.php
Now first file we will update as bellow for Calendar.php file. app/Http/Livewire/Calendar.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Event;

class Calendar extends Component
{
    public $events = '';

    public function getevent()
    {       
        $events = Event::select('id','title','start')->get();

        return  json_encode($events);
    }

    /**
    * Write code on Method
    *
    * @return response()
    */ 
    public function addevent($event)
    {
        $input['title'] = $event['title'];
        $input['start'] = $event['start'];
        Event::create($input);
    }

    /**
    * Write code on Method
    *
    * @return response()
    */
    public function eventDrop($event, $oldEvent)
    {
      $eventdata = Event::find($event['id']);
      $eventdata->start = $event['start'];
      $eventdata->save();
    }

    /**
    * Write code on Method
    *
    * @return response()
    */
    public function render()
    {       
        $events = Event::select('id','title','start')->get();

        $this->events = json_encode($events);

        return view('livewire.calendar');
    }
}
Step 7: Create View

Here, we will create blade file for call fullcalendar route. in this file we will use @livewireStyles, @livewireScripts so let's add it

resources/views/home.blade.php
<html>
<head>
    @livewireStyles
</head>
<body>
    <livewire:calendar />
    @livewireScripts
    @stack('scripts')
</body>
</html>

after,I will create calendar componet blade file.

resources/views/livewire/calendar.blade.php
<style>
    #calendar-container{
        width: 100%;
    }
    #calendar{
        padding: 10px;
        margin: 10px;
        width: 1340px;
        height: 610px;
        border:2px solid black;
    }
</style>

<div>
  <div id='calendar-container' wire:ignore>
    <div id='calendar'></div>
  </div>
</div>

@push('scripts')
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@5.3.1/main.min.js'></script>
    
    <script>
        document.addEventListener('livewire:load', function() {
            var Calendar = FullCalendar.Calendar;
            var Draggable = FullCalendar.Draggable;
            var calendarEl = document.getElementById('calendar');
            var checkbox = document.getElementById('drop-remove');
            var data =   @this.events;
            var calendar = new Calendar(calendarEl, {
            events: JSON.parse(data),
            dateClick(info)  {
               var title = prompt('Enter Event Title');
               var date = new Date(info.dateStr + 'T00:00:00');
               if(title != null && title != ''){
                 calendar.addEvent({
                    title: title,
                    start: date,
                    allDay: true
                  });
                 var eventAdd = {title: title,start: date};
                 @this.addevent(eventAdd);
                 alert('Great. Now, update your database...');
               }else{
                alert('Event Title Is Required');
               }
            },
            editable: true,
            selectable: true,
            displayEventTime: false,
            droppable: true, // this allows things to be dropped onto the calendar
            drop: function(info) {
                // is the "remove after drop" checkbox checked?
                if (checkbox.checked) {
                // if so, remove the element from the "Draggable Events" list
                info.draggedEl.parentNode.removeChild(info.draggedEl);
                }
            },
            eventDrop: info => @this.eventDrop(info.event, info.oldEvent),
            loading: function(isLoading) {
                    if (!isLoading) {
                        // Reset custom events
                        this.getEvents().forEach(function(e){
                            if (e.source === null) {
                                e.remove();
                            }
                        });
                    }
                }
            });
            calendar.render();
            @this.on(`refreshCalendar`, () => {
                calendar.refetchEvents()
            });
        });
    </script>
    <link href='https://cdn.jsdelivr.net/npm/fullcalendar@5.3.1/main.min.css' rel='stylesheet' />
@endpush

Now we are ready to run our example so run bellow command for quick run:

php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/
Preview
Add Event Fullcalendar
Drag And Drop Fullcalendar

It will help you..

Laravel Validation digits Example

Hi Guys,

Today, I will learn you to create validation digits in laravel.we will show example of laravel validation digits.The field under validation must be numeric and must have an exact length of value.

Here, I will give you full example for simply Validation digits in laravel bellow.

solution
$request->validate([
  'rank' => 'required|digits:10',
]);
Route : routes/web.php
Route::get('form/create','FromController@index');
Route::post('form/store','FromController@store')->name('form.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
          'rank' => 'required|digits:10'
        ]);

        dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <scr Validation digitst src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scr Validation digitst>
  <scr Validation digitst src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scr Validation digitst>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation digits Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
                  <div class="row">
                      <div class="col-md-12">
                          <div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                              @foreach($errors->all() as $error)
                              {{ $error }} <br>
                              @endforeach      
                          </div>
                      </div>
                  </div>
                @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Rank No:</label>
                      <input name="rank" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...