Laravel 8 Generate QR Code Example

Hi Guys,

Today,I will learn you how create QR Code in laravel 8 we will show QR Code generator example in laravel 8.I will generator QR Code useing simplesoftwareio/simple-qrcode package in laravel 8. laravel 8 QR Code generator example. in this tutorial, i would like to show you how to generate or create QR Code in laravel 8 using simplesoftwareio/simple-qrcode package.

Using this simplesoftwareio/simple-qrcode package, you can generate simple qr code, qr code, image qr code, text qr code in laravel 8 app. As well as, you can send this qr codes in mail and text message.

In this tutorial, i will use simplesoftwareio/simple-qrcode package to generate simple, text, numeric and image qr code in laravel 8 app.

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 :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 :Installing qrcode Generator Package

Now In this step, install simplesoftwareio/simple-qrcode package in laravel 8 app via following command.

composer require simplesoftwareio/simple-qrcode
Step 4:Configure qrcode Generator Package

Here In this step,I will configure the simplesoftwareio/simple-qrcode package in laravel 8 app. So, Open the providers/config/app.php file and register the provider and aliases for milon/qrcode.

'providers' => [
    ....
    SimpleSoftwareIO\QrCode\QrCodeServiceProvider::class
],
  
'aliases' => [
    ....
    'QrCode' => SimpleSoftwareIO\QrCode\Facades\QrCode::class
]
Step 5:Create Routes

In this step,we will add the qr code generation routes in web.php file, which is located inside routes directory:

<?php
use App\Http\Controllers\QrCodeGeneratorController;
Route::get('/qr-code', [QrCodeGeneratorController::class, 'index']);
Step 6: Creating QrCode Controller

Now this step,I will create generate QrCode controller file by using the following command.

php artisan make:controller QrCodeGeneratorController

After navigate to app/http/controllers and open QrCodeGeneratorController.php file. And add the simple QrCode generation code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use QrCode;

class QrCodeGeneratorController extends Controller
{
    public function index()
    {
      return view('qrCode');
    }
}
Step 7 :Create Blade View

In this last step , create qr-generator blade view file inside resources/views directory. And then add the following code into it.

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 8 Qr Code Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <div class="container">
    <div class="row text-center mt-5">
      <div class="col-md-6">
        <h4>Simple Qr Code</h4>
        {!! QrCode::size(250)->generate('Nicesnippets.com') !!}
      </div>
      <div class="col-md-6">
        <h4>Color Qr Code</h4>
        {!! QrCode::size(250)->backgroundColor(255,55,0)->generate('Nicesnippets.com') !!}
      </div>
    </div> 
  </div> 
</body>
</html>

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/qr-code
It will help you..

JQuery Disable Button on Click To Prevent Multiple Form Submits Example

Hii Dev,

In this example, i will give you simple example in jQuery disable button on click to prevent multiple form submits.

we will lean how to disable button on click to prevent multiple form submits in jquery. we can stop duplicate form submission using jquery. we can easily disabled button on click event in jquery for prevent duplicate form submit. when you click on submit button than it should be disabled so it's click again.

I written example for that, you can use bellow php file. you can see bellow full code. You can also check this small jquery code and full code.

Jquery code
$(document).ready(function () {
    $("#formABC").submit(function (e) {

        //stop submitting the form to see the disabled button effect
        e.preventDefault();

        //disable the submit button
        $("#btnSubmit").attr("disabled", true);

        return true;
    });
});

Here is a full example, you can see.

Full Example
<!DOCTYPE html>
<html lang="en">

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">

<body>
  <form id="formABC">
    <input type="text" name="name" placeholder="Name">
    <input type="text" name="email" placeholder="Email">
   
    <button type="submit" id="btnSubmit">Submit</button>
  </form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


<script>
    $(document).ready(function () {
        $("#formABC").submit(function (e) {

            //stop submitting the form to see the disabled button effect
            e.preventDefault();

            //disable the submit button
            $("#btnSubmit").attr("disabled", true);

            return true;
        });
    });
</script>

</body>
</html>

It will help you...

Jquery Disabled Select Element Tutorial - ItWebtuts

Hi Dev,

In this artical, i will give you disable select using jQuery.If You are looking for a simple way to disable select for any html element then here you will find the best solution to disable select on page.

There are some reasons why you will select text disable.

Example 1

It may be you want to show your own menu html page select text disable on a , useing the jQuery-ui bind() method.


<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<h3>Select text disable on this page.</h3>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

<script>
  $( function() {
    $('body').attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', /* you could also put this in a class */
           '-webkit-user-select':'none',/* and add the CSS class here instead */
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });
  } );
  </script>
</script>
</body>
</html>
Example 2

It may be you want to show your own menu html page select text disable on a useing the jQuery-ui onmousedown() and onselectstart() method.

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body onmousedown = 'return false' onselectstart = 'return false'>

<h3>Select text disable on this page.</h3>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</script>
</body>
</html>
Example 3

It may be you want to show your own menu html page select text disable on a useing the disableSelection() method.

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<h3>Select text disable on this page.</h3>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

<script>
  $( function() {
    $('body').disableSelection();
  } );
  </script>
</body>
</html>

It will help you...

PHP Upload File Using Ckeditor Example - Itwebtuts

Hii Developer,

In this example,I am going to show you How to do upload custom file with CKEDITOR in PHP application. In this tutorial i explain step by step example code of How to image upload with CKEDITOR php.

php ajax image upload with preview example

You can see simple example of php ckeditor custom image upload using browse button.

Here i give you full example of How to How to do custom file upload with in CKEDITOR step by step like create one file in this file we are integrate CKEDITO and secound another file which we are created for uploadin custom file.

Following The Step:

1)create one index.php file

2)create cstom file uploading file

Step:1 Create one index.php file

Now we have download CKEDITOR in our local PC. then we are create our index.php file and this file we are use CKEDITOR

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="robots" content="noindex, nofollow">
    <title>Ckeditor File Upload</title>
    <script src="http://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>
<body>
    <textarea cols="10" id="editor1" name="editor1" rows="10" >
    </textarea>
    <script>
        
        CKEDITOR.replace( 'editor1', {
            height: 300,
            filebrowserUploadUrl: "upload.php",
            
        } );
    </script>
</body>
</html>

now we are create one photos folder. in this folder we are use in our custom file uploading code. our all custom file which we are uploading from PC to CKEDITOR they all file store in this folder.

Step:2 Create Custom file uploading file

Now we are creating our custome file uploading file look like this "/upload.php".

 '/photos/', 
); 
 
// Allowed image properties  
$imgset = array( 
    'maxsize' => 20000, 
    'maxwidth' => 1024, 
    'maxheight' => 800, 
    'minwidth' => 10, 
    'minheight' => 10, 
    'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'), 
); 
 
// If 0, will OVERWRITE the existing file 
define('RENAME_F', 1); 
 
/** 
 * Set filename 
 * If the file exists, and RENAME_F is 1, set "img_name_1" 
 * 
 * $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename 
 */ 
function setFName($p, $fn, $ex, $i){ 
    if(RENAME_F ==1 && file_exists($p .$fn .$ex)){ 
        return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1)); 
    }else{ 
        return $fn .$ex; 
    } 
} 
 
$re = ''; 
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) > 1) { 
 
    define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name'])));   
 
    // Get filename without extension 
    $sepext = explode('.', strtolower($_FILES['upload']['name'])); 
    $type = end($sepext);    /** gets extension **/ 
     
    // Upload directory 
    $upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio']; 
    $upload_dir = trim($upload_dir, '/') .'/'; 
        
    // Validate file type 
    if(in_array($type, $imgset['type'])){ 
        // Image width and height 
        list($width, $height) = getimagesize($_FILES['upload']['tmp_name']); 
 
        if(isset($width) && isset($height)) { 
            if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']){ 
                $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight']; 
            } 
 
            if($width < $imgset['minwidth'] || $height < $imgset['minheight']){ 
                $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight']; 
            } 
 
            if($_FILES['upload']['size'] > $imgset['maxsize']*1000){ 
                $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.'; 
            } 
        } 
    }else{ 
        $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.'; 
    } 
     
    // File upload path 
    $f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0); 
    $uploadpath = $upload_dir . $f_name; 
 
    // If no errors, upload the image, else, output the errors 
    if($re == ''){ 
        if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) { 
            $CKEditorFuncNum = $_GET['CKEditorFuncNum']; 
            $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.'ckeditor/'. $upload_dir . $f_name; 
            $msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB'; 
            $re = in_array($type, $imgset['type']) ? "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>":'<script>var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\' \', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent();dialog.hide();</script>'; 
        }else{ 
            $re = '<script>alert("Unable to upload the file")</script>'; 
        } 
    }else{ 
        $re = '<script>alert("'. $re .'")</script>'; 
    } 
} 
 
// Render HTML output 
@header('Content-type: text/html; charset=utf-8'); 
echo $re;

Now we are ready to run our example.

It will help you...

Laravel Get All Columns From Table Example - ItWebtuts

getTable() method

Hi dev,

In this example,i will get all columns of a table in laravel . we are pick up all columns of model in laravel. it can get all column names of a table in php laravel.

So sometime you may need to get table name from controller into your laravel application and you can easily get table name by using getTable() method.You will see two are lots of method available with Laravel get all columns from table.your laravel application and you can easily get all columns from table using getTable() method.

I can blow you can easily get all columns from table in laravel this example.

Example:1

Here In this exmaple laravel get all columns from table using a schema builder to a getColumnListing method

 /**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
    $user= new User;
    
    $table = $user->getTable();
    
    $columns  = \Schema::getColumnListing($table);

    dd($columns);
}
Output:
array:8 [
  0 => "id"
  1 => "name"
  2 => "email"
  3 => "email_verified_at"
  4 => "password"
  5 => "remember_token"
  6 => "created_at"
  7 => "updated_at"
]
Example:2

Here In this exmaple laravel get all columns from table using a db builder to a getColumnListing method

 /**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
    $user= new User;
    
    $table = $user->getTable();

    $columns = \DB::getSchemaBuilder()->getColumnListing($table);
    
    dd($columns);
}
Output:
array:8 [
  0 => "id"
  1 => "name"
  2 => "email"
  3 => "email_verified_at"
  4 => "password"
  5 => "remember_token"
  6 => "created_at"
  7 => "updated_at"
]

I hope it can help you..

Jquery Search Text From Page With Next And Previous Button Example

 next and previous button jquery

Hi Guys,

Today, I will learn you how to search text from page with next and previous button useing jquery.we will show example of search text. you can easliy search text from page with next and previous button useing jquery.i will use highlight js to make jquery search text from page with next and previous button.

Here, I will give you full example for simply search text from page with next and previous button using jquery as bellow.

Example
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type='text/javascript' src='https://johannburkard.de/resources/Johann/jquery.highlight-4.js'></script>
<style type='text/css'>
    body {
        font-family:Calibri,Tahoma,Verdana; 
        border:2px solid #000;
        padding: 10px;
        text-align: center;
    }
    input {
        font-family: inherit; 
    }
    input[type=button] {
        min-height:24px; min-width:64px; 
    }
    body p {
     font-family:Consolas; text-align:justified; margin: 10px; 0 0 0;
    }
    .highlight {
     background-color:yellow; 
    }
    .emptyBlock1000 {
     height:auto; 
    }
    .emptyBlock2000 {
     height:auto; 
    }
    .current {
     background-color: #957F68 !important; color: #ffffff; 
    }
</style>
</head>
<body>
    <br/>
        <h2>Jquery Search Text From Page With Next And Previous Button - Itwebtuts</h2>
    <form name="frmMain" id="frmMain" method="post">
        <input type="text" id="searchTerm" />
        <input type="button" id="btnNext" value="next" />
        <input type="button" id="btnPrev" value="prev" />
    </form><br/>
    <div id="bodyContainer">
        <p class="emptyBlock1000">
          Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere<br>
          Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere
          Lorem ipsum dolor sit, amet consectetur adipisicing elit. Enim repudiandae deserunt, voluptatum dignissimos. Sint repellat dolore rem, sapiente quis ut, soluta ipsam repellendus, adipisci laudantium odit ipsa quidem quo molestiae!
          Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere
        </p>
    </div>
</body>
<script type='text/javascript'>
var lstEl = null;
var cntr = -1;

$(document).ready(function() {
    $('#searchTerm').keyup(function() {
        lstEl = null;
        cntr = -1;
        var vl = document.getElementById('searchTerm').value;
        $("#bodyContainer").removeHighlight();
        $("#bodyContainer").highlight(vl);
    });

    $('#btnNext').click(function() {
        if (lstEl === null) {
            lstEl = $('#bodyContainer').find('span.highlight');
            if (!lstEl || lstEl.length === 0) {
                lstEl = null;
                return;
            }
        }
        if (cntr < lstEl.length - 1) {
            cntr++;
            var cntrlast = cntr -1;
            if (cntr > 0) {
                $(lstEl[cntrlast]).removeClass('current');
            }

            var elm = lstEl[cntr];
            $(elm).addClass('current');
        } else
            alert("End of search reached!");
    });

    $('#btnPrev').click(function() {
        if (lstEl === null) {
            lstEl = $('#bodyContainer').find('span.highlight');
            if (!lstEl || lstEl.length === 0) {
                lstEl = null;
                return;
            }
        }
        if (cntr > 0) {
            cntr--;
            if (cntr < lstEl.length) {
                $(lstEl[cntr + 1]).removeClass('current');
            }
            var elm = lstEl[cntr];
            $(elm).addClass('current');
        } else
            alert("Begining of search!");
    });
});
</script>
</html>

It will help you...

Laravel One to Many Eloquent Relationship Tutorial

laravel one to Many eloquent relationship

Hi Dev,

In this tutorial, I Will explain you how to create laravel one to Many eloquent relationship. We will create one to many relationship in laravel. We will learn how we can create migration with foreign key schema, retrieve records, insert new records, update records etc. I will show you laravel hasMany relationship example.

We will create "employee" and "salary" table.both table are connected with each other, I will create one to many relationship with each other by using laravel Eloquent Model, We will first create database migration, then model, retrieve records and then how to create records too.One to Many Relationship use "hasMany()" and "belongsTo()" for relation.

Here, I will give you full example for laravel one to many eloquent relationship as bellow.

Step:1 Create Migration

In this example, we will need two tables in our database employee and salary.I will start to create the model and migrations, then we will define the one to hasMany relationship.To generate models and migrations, run below two commands in your terminal.

php artisan make:model Employee -m

php artisan make:model Salary -m

Above command will generate two models in your app folder called Employee and Salary. You will also find two new migrations in your database/migrations folder.

Your newly created models and migration after add table field: Path:database\migrations\2014_10_12_000000_create_employee_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEmployeeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employee', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('salary_id');
            $table->integer('extra_salary_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employee');
    }
}
Path:database\migrations\2014_10_12_000000_create_salary_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateSalaryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('salary', function (Blueprint $table) {
            $table->id();
            $table->integer('amount');
            $table->date('payment_date');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('salary');
    }
}
Now run the below command to create employee and salary tables in your database:
php artisan migrate
Step:2 Create Model Relationship

Now in this step, we have employee and Salary tables ready, let’s define the one to manMany relationship in our models. our app/Employee.php model file and add a new function called salary() which will return a hasMany relationship like below:

app\Employee.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = [
        'name','salary_id','extra_salary_id'
    ];
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function salary()
    {
        return $this->belongsTo(Salary::class);
    }
}

you can see, in the salary() method we are defining a hasMany relationship on Salary model.

Now we will defining Inverse One To Many Relationship in Laravel.As we have defined the hasMany relationship on Brand model which return the related records of Salary model, we can define the inverse relationship on the Salary model.Open your app/Salary.php model file and add a new method called employee() in it which will return the related brand of a Salary.

app\salary.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Salary extends Model
{
   /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = ['amount','payment_date'];
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function employer()
    {
        return $this->hasMany(Employer::class);
    }
}

As you can see, in employee() method we are returning a belongs to relation which will return the related employee of the salary.

Step 3 : Insert Records

Let’s in this step add data to employee and salary from controller:

app\Http\Controllers\Employee.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Salary;
use Hash;

class EmployeeController extends Controller
{
    public function Employee()
    {   
        $employee = employee::find(1);
        $employee->name = "Test Name";
        $employee->salary_id ="1"
        $employee->extra_salary_id ="2"
        
        $employee = $employee->salary()->save($employee);
    }
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Salary;
use Hash;

class EmployeeController extends Controller
{
    public function Salary()
    {
        $employee = employee::find(1);

        $salary1 = new Salary;
        $salary->amount = '123456789';
        $salary->payment_date = '15/07/2020';
        
        $salary2 = new Salary;
        $salary->amount = '123456789';
        $salary->payment_date = '16/07/2020';
        
        $employee = $employee->salary()->saveMany([$salary1, $salary2]);

    }
}
Step 4 : Retrieve Records

Now in this step retrieve records model

app\Http\Controllers\Employee.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employee;
use App\Salary;
use Hash;

class EmployeeController extends Controller
{
    public function index()
    {
        $employee = Employee::find(1);
 
        $employee = $employee->salary;
 
        dd($employee);

        $salary = Salary::find(1);
 
        $salary = $salary->employee;
         
        dd($salary);
    }
}
it will help you....

PHP Create,Access,and Destroy Cookies Tutorial

create,access,and destroy cookies in php

Hi Guys,

In this blog,I will explain you how to create,access,and destroy cookies in php a cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.They are typically used to keeping track of information such as a username that the site can retrieve to personalize the page when the utilizer visits the website next time.A cookie can only be read from the domain that it has been issued from.Cookies are conventionally set in an HTTP header but JavaScript can withal set a cookie directly on a browser.

Tip:Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.
Setting a Cookie in PHP

The setcookie() function is utilized to set a cookie in PHP. Ascertain you call the setcookie() function before any output engendered by your script otherwise cookie will not set. The basic syntax of this function can be given with:

Syntax:
setcookie(name, value, expire, path, domain, secure);

The parameters of the setcookie() function have the following meanings:

  1. Name:It is used to set the name of the cookie.
  2. Value:It is utilized to set the value of the cookie.
  3. Expire:It is utilized to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
  4. Path:It is utilized to designate the path on the server for which the cookie will be available.
  5. Domain: It is used to specify the domain for which the cookie is available.
  6. Security:It is utilized to denote that the cookie should be sent only if a secure HTTPS connection exists.
Tip:

If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e. when the browser closes.

Creating Cookies:

Here's an example that utilizes setcookie() function to engender a cookie named username and assign the value value Dharmik to it. It additionally specify that the cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec).

<?php  

  // Setting a cookie
  setcookie("username", "Dharmik", time()+30*24*60*60);

?>
Note:

Only the designation argument in the setcookie() function is obligatory.To skip an argument,the argument can be replaced by a vacuous string(“”).

Warning:

Don't store sensitive data in cookies since it could potentially be manipulated by the maleficent utilizer. To store the sensitive data securely use sessions instead.

Accessing Cookies Values

The PHP $_COOKIE superglobal variable is utilized to retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The individual cookie value can be accessed utilizing standard array notation, for example to display the username cookie set in the precedent example, you could utilize the following code.

Example
<?php

  // Accessing an individual cookie value
  echo $_COOKIE["username"];

?>
Output
Dharmik

It's a good practice to check whether a cookie is set or not before accessing its value. To do this you can utilize the PHP isset() function, like this:

Example
<?php

  // Verifying whether a cookie is set or not
  if(isset($_COOKIE["username"])){
      echo "Hi " . $_COOKIE["username"];
  } else{
      echo "Welcome MyWebtuts.com";
  }

?>

You can utilize the print_r() function like print_r($_COOKIE); to optically discern the structure of this $_COOKIE associative array, like you with other arrays.

Removing Cookies

You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as a empty string) however this time you require the set the expiration date in the past, as shown in the example below:

Example
<?php

// Deleting a cookie
setcookie("username", "", time()-3600);

?>
Note:

The same path, domain, and other arguments should be passed that were used to engender the cookie in order to ascertain that the correct cookie is deleted.

It will help you..

Laravel Validation email Tutorial

validation email in laravel

Hi Dev,

Today, I will learn you to create validation email in laravel.we will show example of laravel validation email.The field under validation must be formatted as an e-mail address

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

solution
$request->validate([
  'email' => 'required|email',
]);
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([
            'email' => 'required|email',
        ]);
        
        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 email 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>Email:</label>
                      <input name="email" 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...

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...