Laravel 8 Create Custom Namespace Tutorial

Laravel 8 Create Custom Namespace Tutorial

Hi Dev,

In this post,I will give you how to create custom namespace in laravel 8. we will show example of laravel 8 create custom namespace. laravel 8 namespaces are defined as a class of elements in which each element has a unique name to the associated class. the namespaces may be shared with elements in other classes. let’s understand why we need a namespace in laravel 8.

Here, I will give you full example for laravel 8 create custom namespace as bellow.

Create Custom Namespace in Laravel 8

I will create a custom namespace in Laravel 8, create a separate controller with forward-slash(/) using the following command.

php artisan make:controller Client/UserController --resource --model=User

If you closely look at the above command, you can see that we have used the forward slash to separate our namespace Client. This gives us the ability to create a custom namespace, and it is easier for us to design the project.

The UserController will be created inside the Client directory inside the app >> Http >> Controllers folder.

Also, we have attached the User.php model to the UserController.

If you open the UserController.php file, then it looks like below.

<?php

// UserController.php

namespace App\Http\Controllers\Client;

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}

You can see that our new namespace is App\Http\Controllers\Client;

That means if in the future, we have to create a functionality related to the Client module, then we will create another controller Client the Admin namespace.

Other examples like if you are creating an API for a mobile application, then you should make an API namespace and all the controllers will be included under the API namespace

How does routing work under a new namespace?

To write Admin namespace routes, open web.php file and add the following code.

routes/web.php
<?php
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| 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::namespace('Client')->group(function() {
    Route::resource('users', 'UserController');
});

You can see that we are explicitly defining the routes for the Admin namespace.

Under the Admin namespace, we are defining all the client related routes.

Now, go to the UserController’s index() method and add the following code.

// UserController.php

public function index()
{
    return 'Yes!! Client namespace is working successfully';
}

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/users

It will help you...

Laravel One to One Eloquent Relationship Tutorial

laravel hasone relationship

Hi Dev,

Today,I will learn you how to use hasone relationship in laravel. This is a short guide on laravel if hasone relationship. We will use how to use hasone relationship in laravel. Here you will learn how to use hasone relationship in laravel. We will use how to use if hasone relationship in laravel. Let's get started with how to hasone relationship use in laravel.

Here i will give you many example how you can check hasone relationship in laravel.

Create Migrations:

Now we have to create migration of "Products" and "ProductCategories" table. so let's create like as below:

Products table migration:

<?php

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('sub_title');
            $table->integer('product_category_id');
            $table->text('description');
            $table->string('image');
            $table->string('client');
            $table->date('date');
            $table->timestamps();
        });
    }

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

ProductCategories table migration:

<?php

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

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

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('Product_categories');
    }
}
?>
Create Models:

Here, we will create Product and ProductCategory table model. we will also use "hasOne()" for relationship of both model.

Product Model:

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    public $table = 'Products';
   
    public $fillable = ['title','sub_title','product_category_id','description'];

    /**
        * Write code on Method
        *
        * @return response()
    */
    public function ProductCategory(){
        return $this->hasOne(ProductCategory::class, 'id', 'product_category_id');
    }
}
?>

ProductCategory Model:

<?php

namespace App\Models;

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

class Product_Category extends Model
{
    use HasFactory;

    public $table = 'Product_categories';
   
    public $fillable = ['name'];
}
?>

Retrieve Records:

$ProductCategory = Product::find(1)->ProductCategory;
dd($ProductCategory);
$Product = ProductCategory::find(1)->Product;
dd($Product);

Create Records:

$Product = Product::find(1);
 
$ProductCategory = new ProductCategory;
$ProductCategory->ProductCategory->name = 'Mobile';
 
$Product->ProductCategory()->save($ProductCategory);
$ProductCategory = ProductCategory::find(1);
 
$Product = Product::find(10);
 
$ProductCategory->Product()->associate($Product)->save();

It will help you....

Jquery Get Current Page Url Tutorial

Hii guys,

Today, I will show you how to get the current page url using jquery.In most cases while working with JavaScript, we sometime need to get current URL with or without query string.

There are so many ways to get the current URL of web page.

You may need current URL at the time of redirection or you can perform so many other task with current URL.

Solution: 1

First Solution Using window.location.href

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            var currentURL = window.location.href;
            alert(currentURL);
        });
    });
</script>
</head>
<body>
    <button type="button">Get URL</button>
</body>
</html>

If return alert in show current page URL

Solution: 2

Second Solution Using $(location).attr("href")

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            var currentURL = $(location).attr("href");
            alert(currentURL);
        });
    });
</script>
</head>
<body>
    <button type="button">Get URL</button>
</body>
</html> 

If return alert in show current page URL

Solution 3

Third Solution Using window.location

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
             var currentURL = window.location;
       alert(currentURL);
        });
    });
</script>
</head>
<body>
    <button type="button">Get URL</button>
</body>
</html>                            

If return alert in show current page URL

Solution: 4

Fourth Solution Using location.protocol + '//' + location.host + location.pathname

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            var currentURL=location.protocol + '//' + location.host + location.pathname;
        alert(currentURL);
        });
    });
</script>
</head>
<body>
    <button type="button">Get URL</button>
</body>
</html>                            

If return alert in show current page URL

It will help you...

Laravel Routing Tutorial | Laravel Routing Example

Laravel 8 Routing Example

Hi dev,

In this example,I will describe you step by step laravel 8 routing tutorial. I will learn how to create new route in laravel 8. you can easily create post route in laravel 8 application. i will also show how to create route in laravel 8 controller.

I will step by step process of how to create first route in laravel and understanding of laravel routing with brief.

What is Laravel Routing?

Using Routing you can create a request URL for your application. you can design set of HTTP request like POST Request, GET Request, PUT Request and DELETE Request using routing in laravel 8.

You can easily create route in web.php file inside a routes folder. in web.php file you can create your route list there are several ways. i will show you bellow step by step how you can create it and how it works, so let's see step by step explanation.

Create Simple Route:

Now, I will create very simple route and will let you know how you can access it. so let's create simple route using following line adding in route file:

routes/web.php
Route::get('simple-route', function () {
    return 'This is Simple Route Example of itwebtuts.com';
});
Access URL:
http://localhost:8000/simple-route
Route with Call View File:

You can create route with directly call view blade file from route directly. You can see bellow created route example:

you may use the Route::view method. Like the redirect method, this method provides a simple shortcut so that you do not have to define a full route or controller. The view method accepts a URI as its first argument and a view name as its second argument. In addition, you may provide an array of data to pass to the view as an optional third argument:

routes/web.php
Route::view('/blog', 'index');

Route::view('/blog', 'index', ['name' => 'itwebtuts']);
resources/views/index.php
<h1>his is Simple Route with Call View File Example of itwebtuts.com</h1>
Access URL:
http://localhost:8000/blog
Route with Controller Method:

Here, you can create route with call controller method so, you can simply create controller method and call that method with your route as like bellow:

routes/web.php
use App\Http\Controllers\PostController;
// PostController
Route::get('/post', [PostController::class, 'index']);
app/Http/Controllers/PostController.php
<?php
  
namespace App\Http\Controllers;
  
class PostController extends Controller
{
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('index');
    }
}
resources/views/index.php
<h1>his is Simple Route with Controller Method Example of itwebtuts.com</h1>
Access URL:
http://localhost:8000/post
Create Route with Parameter:

Here, we will create simple route with passing parameters. you can can create dynamic route with your controller. so let's create as bellow

routes/web.php
use App\Http\Controllers\PostController;
// PostController
Route::get('/post/{id}', [PostController::class, 'show']);
app/Http/Controllers/PostController.php
<?php
  
namespace App\Http\Controllers;
  
class PostController extends Controller
{
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function show($id)
    {
        return 'Post ID:'. $id;
    }
}
Access URL:
http://localhost:8000/post/15
Create Route Methods:

You can create get, post, delete, put, patch methods route as bellow i created. you can understand how it works.

So, let's see bellow route examples:

<?php
use App\Http\Controllers\UserController;
// UserController
Route::get('users', '[UserController::class, 'index']');
Route::post('users', '[UserController::class, 'post']');
Route::put('users/{id}', '[UserController::class, 'update']');
Route::delete('users/{id}', '[UserController::class, 'delete']');
You can also check how many routes i created using following command:
php artisan route:list

You can also create resource routes as i written tutorial on it. You can see here: Create Resource Routes in Laravel.

I will help you...

Laravel Generate URLs to Named Routes Tutorial

Hi Guys,

In this blog, i will give you simaple example of generate urls to named routes in laravel. we are create examples of url to named route.

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface.

Example 1: Basic Url To Routes

Laravel provides a global route() function that gets the URL to a named route. The only one Parameter is the route name (string).

Simple example, it would look as routes/web.php file defines routes that are for your web interface:

Basic Route:
<?php
use App\Http\Controllers\HomeController;

Route::get('Home', ['HomeController::class','index'])->name('home');

or

This is achieved by chaining the name() method to the route definition:

Route::get('Home', function() {
    return view('home');
})->name('home');

Simple example, as it would look as an anchor tag within in a Blade template:

Basic url:
Simple url To route
Example: Single Parameter Url To Routes

Laravel provides a global route() function that gets the URL to a named route. The first Parameter is the route name (string). Depending on the route you’re trying to access you may also need to pass in an array of parameters as the second argument.

Example 2: Single Parameter Route:

Simple example, it would look as routes/web.php file defines routes that are for your web interface:

<?php
use App\Http\Controllers\PostsController;

Route::get('posts/{id}', ['PostsController::class','show'])->name('post');

Simple example, as it would look as an anchor tag within in a Blade template:

Link to Resource {{ $id }}

It will help you...

Php Datatables Delete Multiple Selected Rows Tutorial

Hi Dev,

In this blog, I will explain you how to delete multiple selected records useing datatables in php. We will show delete multiple selected records in php. you can easy delete multiple selected records useing datatables in php. we will show datatables delete multiple selected rows example in php.

I will give fulll example of php delete multiple selected records in datatables.

Step 1: Cretae Table

In this step, i will create table in mysql database.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(80) NOT NULL,
  `salary` varchar(20) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `city` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 
Step 1:Configuration

In this step, I will create php to mysql datatables configuration.

config.php
<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = "root"; /* Password */
$dbname = "php_tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}
Step 2: HTML

In this step,Create a <table id='empTable' class='display dataTable' >. Add header row.

In the last cell add check all checkbox and a button for deleting checked records.

<!doctype html>
<html>
    <head>
        <title>Delete multiple selected records in DataTables – PHP</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
        <!-- Datatable CSS -->
        <link href='//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>

        <!-- jQuery Library -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <!-- Datatable JS -->
        <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
        
        <!-- Bootstrap  Cs-->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
    </head>
    <body class="bg-dark">
        <div class="container">
          <div class="row">
              <div class="col-md-10 offset-md-1">
                  <div class="card mt-1">
                      <div class="card-header">
                          <h5>PHP Delete multiple selected records in DataTables – nicesnippets.com</h5>
                      </div>
                      <div class="card-body">
                            <!-- Table -->
                        <table id='empTable' class='display dataTable table table table-hover'>
                            <thead>
                            <tr>
                                <th>Employee name</th>
                                <th>Email</th>
                                <th>Gender</th>
                                <th>Salary</th>
                                <th>City</th>
                                <th>Check All <input type="checkbox" class='checkall' id='checkall'><input type="button" id='delete_record' class="btn btn-sm ml-3 btn-danger" value='Delete' ></th>
                            </tr>
                            </thead>
                        </table>
                      </div>
                  </div>
              </div>
          </div>
        </div>
    </body>
</html>
Step 3: Script

->DataTable Initialization –

Initialize DataTable on <table id='empTable'>.

Add 'processing': true, 'serverSide': true, 'serverMethod': 'post'. Specify AJAX url, and data using 'ajax' option.

Using 'columns' option to specify field names which need to be read from AJAX response.

Remove sorting from the last column using columnDefs option.

->Check All –

If checkall checkbox is clicked then check it is checked or not. If checked then set all checkboxes checked by class='delete_check'.

If not checked then remove checked from all checkboxes.

>->Checkbox checked –

Create a checkcheckbox() function.

Count total checkboxes and checked checkboxes with class='delete_check' on the page.

If total checkboxes equal to total checked checkboxes then check the checkall checkbox otherwise uncheck the checkbox.

->Delete button –

Read all checked checkboxes by class='delete_check' and push value in deleteids_arr Array.

If deleteids_arr Array length is greater then display confirm alert. Send AJAX POST request to ‘ajaxfile.php’ for deleting

records when ok button gets clicked.

Pass request: 2, deleteids_arr: deleteids_arr as data.

On successful callback reload the Datatable by calling

dataTable.ajax.reload().
var dataTable;
$(document).ready(function(){

   // Initialize datatable
   dataTable = $('#empTable').DataTable({
     'processing': true,
     'serverSide': true,
     'serverMethod': 'post',
     'ajax': {
        'url':'ajaxfile.php',
        'data': function(data){
           
           data.request = 1;

        }
     },
     'columns': [
        { data: 'emp_name' },
        { data: 'email' },
        { data: 'gender' },
        { data: 'salary' },
        { data: 'city' },
        { data: 'action' },
     ],
     'columnDefs': [ {
       'targets': [5], // column index (start from 0)
       'orderable': false, // set orderable false for selected columns
     }]
   });

   // Check all 
   $('#checkall').click(function(){
      if($(this).is(':checked')){
         $('.delete_check').prop('checked', true);
      }else{
         $('.delete_check').prop('checked', false);
      }
   });

   // Delete record
   $('#delete_record').click(function(){

      var deleteids_arr = [];
      // Read all checked checkboxes
      $("input:checkbox[class=delete_check]:checked").each(function () {
         deleteids_arr.push($(this).val());
      });

      // Check checkbox checked or not
      if(deleteids_arr.length > 0){

         // Confirm alert
         var confirmdelete = confirm("Do you really want to Delete records?");
         if (confirmdelete == true) {
            $.ajax({
               url: 'ajaxfile.php',
               type: 'post',
               data: {request: 2,deleteids_arr: deleteids_arr},
               success: function(response){
                  dataTable.ajax.reload();
               }
            });
         } 
      }
   });

});

// Checkbox checked
function checkcheckbox(){

   // Total checkboxes
   var length = $('.delete_check').length;

   // Total checked checkboxes
   var totalchecked = 0;
   $('.delete_check').each(function(){
      if($(this).is(':checked')){
         totalchecked+=1;
      }
   });

   // Checked unchecked checkbox
   if(totalchecked == length){
      $("#checkall").prop('checked', true);
   }else{
      $('#checkall').prop('checked', false);
   }
}
step 4: PHP

In this step, I will create ajaxfile.php file

->AJAX requests –

If $request == 1 then read DataTables POST values. If $searchQuery is not empty then prepare search query. Count total records without and with filter.

Fetch records from employee table where specify search query, order by and limit.

Loop on the fetched records and initialize $data Array with the keys specified in the columns option while dataTable initializing.

Assign checkbox in ‘action’ key. In the checkbox added onclick=‘checkcheckbox()’, pass $row[‘id’] in value attribute and class=‘delete_check’.

Assign required keys with values in $response Array and return in JSON format.

If $request == 2 then loop on the $deleteids_arr Array and execute DELETE query on the id.

<?php
include 'config.php';

$request = $_POST['request'];

// Datatable data
if($request == 1){
   ## Read value
   $draw = $_POST['draw'];
   $row = $_POST['start'];
   $rowperpage = $_POST['length']; // Rows display per page
   $columnIndex = $_POST['order'][0]['column']; // Column index
   $columnName = $_POST['columns'][$columnIndex]['data']; // Column name
   $columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
   $searchValue = $_POST['search']['value']; // Search value

   ## Search 
   $searchQuery = " ";
   if($searchValue != ''){
      $searchQuery .= " and (emp_name like '%".$searchValue."%' or 
                        email like '%".$searchValue."%' or 
                        city like'%".$searchValue."%' ) ";
   }

   ## Total number of records without filtering
   $sel = mysqli_query($con,"select count(*) as allcount from employee");
   $records = mysqli_fetch_assoc($sel);
   $totalRecords = $records['allcount'];

   ## Total number of records with filtering
   $sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
   $records = mysqli_fetch_assoc($sel);
   $totalRecordwithFilter = $records['allcount'];

   ## Fetch records
   $empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
   $empRecords = mysqli_query($con, $empQuery);
   $data = array();

   while ($row = mysqli_fetch_assoc($empRecords)) {
      $data[] = array(
         "emp_name"=>$row['emp_name'],
         "email"=>$row['email'],
         "gender"=>$row['gender'],
         "salary"=>$row['salary'],
         "city"=>$row['city'],
         "action"=>"<input type='checkbox' class='delete_check' id='delcheck_".$row['id']."' onclick='checkcheckbox();' value='".$row['id']."'>"
      );
   }
   ## Response
   $response = array(
      "draw" => intval($draw),
      "iTotalRecords" => $totalRecords,
      "iTotalDisplayRecords" => $totalRecordwithFilter,
      "aaData" => $data
   );

   echo json_encode($response);
   exit;
}
// Delete record
if($request == 2){
   $deleteids_arr = $_POST['deleteids_arr'];

   foreach($deleteids_arr as $deleteid){
      mysqli_query($con,"DELETE FROM employee WHERE id=".$deleteid);
   }

   echo 1;
   exit;
}

It will help you...

Jquery Set Custom Data Attribute Value Example

Hii guys,

In this artical, we will learn how to get custom attribute value in jquery and how to set custom attribute value in jquery. we will use attr() and data() for getting custom attribute value and set custom attribute value in js.

We can easily set data attribute value in jquery, also you can do it same thing with custom attribute value in jquery.

Example 1:

First Example Using jquery data() function


<!DOCTYPE html>
<html>
<head>
    <title>Jquery Set custom data attribute value</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
  
<div id="example1">Click Here:</div><br>
<button class="set-attr">Set Attribute</button>

<script type="text/javascript">
 
$(".set-attr").click(function(){
    $("#example1").data('my-name', 'nicesnippets');

    var name = $("#example1").data('my-name');
    alert(name);
});
  
</script>
  
</body>
</html>
Example 2:

Second Example Using jquery attr() function

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Set custom data attribute value</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
  
<div id="example1">Click Here:</div><br>
<button class="set-attr">Set Attribute</button>

<script type="text/javascript">
 
$(".set-attr").click(function(){
    $("#example1").attr('my-name', 'nicesnippets');

    var name = $("#example1").attr('my-name');
    alert(name);
});
  
</script>
  
</body>
</html>

It will help you...

Laravel 8 Multiple Image Upload Example

Hi Guys,

In this tutorial, I will learn you how to create multiple image upload in laravel 8. We will show example of laravel 8 multiple image upload.Here you will learn laravel 8 multiple images upload. We will look at example of multiple image upload laravel 8. this example will help you laravel 8 multiple image upload with preview. Alright, let’s dive into the steps.

I will create simple multiple image upload in laravel 8. So you basically use this code on your laravel 8 application.I are going from starch so, we will upload multiple file and store on server then after we will store database too. so in this example we will create "files" table using laravel migration and write code for route, controller and view step by step.

Here, I will give you full example for laravel 8 multiple image upload as bellow.

Step-1:Download Laravel 8 Fresh New Setup

First, we need to download the laravel fresh setup. Use the below command and download fresh new laravel setup :

composer create-project --prefer-dist laravel/laravel blog
Step 2: Add Migration and Model

Here, we need create database migration for files table and also we will create model for files table.

php artisan make:migration create_files_table
<?php

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

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

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

Next I will create File model by using following command:

php artisan make:model File
app/Models/File.php
<?php

namespace App\Models;

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

class File extends Model
{
    use HasFactory;

    protected $fillable = [
        'files'
    ];
}
Step 3: Create Routes

In next step, we will create routes for multiple file upload. so create two route with GET and POST route example.

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\MultipleFileUploadController;
  
/*
|--------------------------------------------------------------------------
| 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!
|
*/
// MultipleFileUploadController
Route::get('/multiple-file-upload', [MultipleFileUploadController::class, 'index'])->name('multiple.file.upload.index');
Route::post('/multiple-file-upload/store', [MultipleFileUploadController::class, 'store'])->name('multiple.file.upload.store');
Step 4: Create Controller

Here I require to add new MultipleFileUploadController controller for manage route So let's create MultipleFileUploadController with create and store method. Make sure you need to create "files" folder in your public directory.

app/Http/Controllers/MultipleFileUploadController.php
<?php

namespace App\Http\Controllers;

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

class MultipleFileUploadController extends Controller
{
    public function index()
    {
      return view('multipleFileUpload');
    }

    public function store(Request $request)
    {
      $this->validate($request, [
            'files' => 'required'
        ]);
  
        $files = [];
        if($request->hasfile('files')){
          foreach($request->file('files') as $file){
              $name = time().rand(1,100).'.'.$file->extension();
              $file->move(public_path('files'), $name);  
              $files[] = $name;  
          }
      }

    File::create(['files' => json_encode($files)]);
  
        return back()->with('success', 'Files uploaded successfully');
    }
}
Store Image in Storage Folder
$request->image->storeAs('images', $imageName);
// storage/app/images/file.png
Store Image in Public Folder
$request->image->move(public_path('images'), $imageName);
// public/images/file.png
Store Image in S3
$request->image->storeAs('images', $imageName, 's3');
Step 5: Create Blade File

in this step we need to create multipleFileUpload.blade.php file in resources folder. So let's multipleFileUpload file:

resources/views/multipleFileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Multiple File Upload</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha256-NuCn4IvuZXdBaFKJOAcsU2Q3ZpwbdFisd5dux4jkQ5w=" crossorigin="anonymous" />
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-3 mt-5">
            <div class="card mt-5">
                <div class="card-header text-center bg-primary">
                    <h2 class="text-white"> <strong>Multiple File Upload</strong></h2>
                </div>
                <div class="card-body">
                  @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>
                @endif
                    @if (count($errors) > 0)
                        <ul class="alert alert-danger pl-5">
                          @foreach($errors->all() as $error)
                             <li>{{ $error }}</li> 
                          @endforeach
                        </ul>
                    @endif
                    <form method="post" action="{{ route('multiple.file.upload.store') }}" enctype="multipart/form-data">
              @csrf
              <div class="input-group file-div control-group lst increment" >
                <input type="file" name="files[]" class="myfrm form-control">
                <div class="input-group-btn"> 
                  <button class="btn btn-success add-btn" type="button"><i class="fldemo fa fa-plus"></i></button>
                </div>
              </div>
              <div class="clone hide">
                <div class="file-div control-group lst input-group" style="margin-top:10px">
                  <input type="file" name="files[]" class="myfrm form-control">
                  <div class="input-group-btn"> 
                    <button class="btn btn-danger" type="button"><i class="fldemo fa fa-close"></i></button>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-md-12 text-center mt-4">
                  <button type="submit" class="btn btn-success rounded-0"><i class="fa fa-save"></i> Save</button>
                </div>
              </div>
          </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function() {
      $(".add-btn").click(function(){
          var lsthmtl = $(".clone").html();
          $(".increment").after(lsthmtl);
      });
      $("body").on("click",".btn-danger",function(){
          $(this).parents(".file-div").remove();
      });
    });
</script>
</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/multiple-file-upload

It Will help you...

PHP Remove Extension From a Filename with Tutorial

Hi guys,

In this blog, i will explain how to remove extension from a filename.If you’ve got a filename that you need to remove the extension from with PHP.We will show remove extension from a filename. i will using pathinfo(), basename(),etc different function to remove file name extension.

Here following the remove extension from a filename exmaple.

Solution 1: Using pathinfo()

Now in this exmaple, The pathinfo() function returns an array containing the directory name, basename, extension and filename.Alternatively, you can pass it one of the PATHINFO_ constants and just return that part of the full filename.

$fileName = 'itwebtutsFileName.html';
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
output
itwebtutsFileName
Solution 2: Using basename()

Here in this exmaple, If the extension is known and is the same for the all the filenames, you can pass the second optional parameter to basename() to tell it to strip that extension from the filename.

$fileName = 'itwebtutsFileName.html';
$withOutExtension = basename($fileName, '.html');
output
itwebtutsFileName
Solution 3: Using substr() and strrpos()

Blow in this exmaple, If the filename contains a full path, then the full path and filename without the extension is returned. You could basename() it as well to get rid of the path if needed (e.g. basename(substr($filename, 0, strrpos($filename, ".")))) although it’s slower than using pathinfo.

$fileName = 'itwebtutsFileName.html';
$withOutExtension = substr($fileName, 0, strrpos($fileName, "."));
output
itwebtutsFileName

It will help you...

PHP Pagination with MySQL and Bootstrap Tutorial

Hi Guys,

In this blog, I will learn you PHP pagination PHP is mostly used to store and display data from a database. Pagination can be done with ajax, but here this is done with non-ajax. In this tutorial, we will learn the pagination in PHP with MySQL. Let's take a brief review about pagination with an example -

It is possible that a SQL SELECT query may returns millions of records back. It is not a good idea to display all records on a single page. A large list of records on a single page may take so much time to load the page and also consume time to find specific data. This may cause (leads to) the confusion in user's mind. Therefore, divide these records over several pages according to the user requirement.

So, what can we do to distribute these large number of records in number of pages? The method of distributing a single list into multiple pages is known as Pagination. Paging refers to showing your query result on multiple pages instead of a single page.

What is Pagination?

Pagination is a way of showing the data on multiple pages rather than putting them to a single page. Pagination avails to divide the records onto several pages, which makes the data more readable and understandable.

Pagination is a prevalent task for PHP developers. MySQL avails the developer to engender pagination by utilizing LIMIT clause, which takes two arguments. The first argument as OFFSET and the second argument is number of records that will return from database.

Let's look at some advantages and disadvantages of using pagination concept in PHP -

Advantages of Pagination
  • Pagination is very useful in astronomically immense scale projects because it makes the webwork more professional. Not only more professional, but it additionally makes the webpage work much more expeditious, precise, and efficient.
  • With the help of pagination, we can save the loading time of a page by dividing the data on various pages. It saves us from loading a lot of information at once. For Example - A webpage with 1000 images will take more time to load images than the 50 images on each webpage. This means that thousands of images need thousands of HTTP requests, which would make the page unresponsive. This problem is resolved by limiting the amount of data with the help of pagination using LIMIT clause.
  • The use of pagination improves the user experience, advertising revenue, and decrease the loading time of the page.
Disadvantages of Pagination

While there are some powerful advantages of pagination, but still many developers avoid to use it. Along with some powerful advantages, there are few disadvantages of pagination as well, which are as follows:

  • Pagination itself is a big overhead in PHP, which is one of the disadvantages of pagination. It is completely an overhead as it is an external feature that can be implemented to the cost of extraneous Markup, Styling, and logic. A small dataset often ignored to use pagination.
  • Pagination may cause of low page rank on search engine because when a page is away from the home page and requires several clicks, it usually does not get a high page rank.
  • It also limits the number links, social shares, total number of results to visible on the webpage, and anchor text that a page receives when the information is split over several pages.
Implementation of Pagination with PHP and MySQL

In order to implement the pagination, we require an astronomically immense dataset to apply pagination to it. Ergo, first we require to engender a database and table. After that, provide the records in the table and commence coding to engender pagination. So that the data fetched from the database can be split over several pages.

Here we will introduce two examples of pagination. First example is a simple and basic example of pagination creation with no CSS, whereas in second example, we will create pagination in attractive way using CSS and bootstrap. You can see the output for both. Below are the steps given for pagination creation;

Simple steps to create pagination -

  1. Create a database and table. Provide a list of records into the table.
  2. Connect with the MySQL database.
  3. Create the pagination link to split the data on multiple pages and add them to bottom of the table.
  4. Fetch data from the database and display it to the multiple pages.

Follow the below step one by one and create simple pagination.

Example

The below example is another example of pagination in which we used CSS along with HTML to make webpage view more attractive. CSS makes the webpage more creative and attractive. On the other hand, MySQL stores the data in database. So, you can learn pagination much better.

We have written whole code in a single file except database connectivity. Therefore, we will create two files, i.e., connection.php and index1.php. Save both the files in .php extension. In the example below, you will learn to create pagination more creative and attractive.

File: connection.php

Database Connectivity

You can write database connectivity code in the same file as well as also keep it separate into another file and include it to your required PHP file. Code for database connection-

<?php  

    $conn = mysqli_connect('localhost', 'root', 'root');  
    if (! $conn) {  
             die("Connection failed" . mysqli_connect_error());  
    }  
    else {  
             mysqli_select_db($conn, 'php_curd');  

    } 

?>

Fetch data and display on webpage

As we have created dataset, now we need to fetch and display it to various webpages. The below code is used to retrieve the data from database and display on the webpages that are divided accordingly.

Fetch data

After establishing the database connection in "connection.php" file, we just need to import it into our code using require_once keyword. We will explicitly define the number of records per page to show.

<?php  

    require_once "connection.php";   
  
    $per_page_record = 4;  // Number of entries to show in a page.   
    // Look for a GET variable page if not found default is 1.        
    if (isset($_GET["page"])) {    
          $page  = $_GET["page"];    
     }    
     else {    
           $page=1;    
     }    
        
    //determine the sql LIMIT starting number for the results on the displaying page  
     $start_from = ($page-1) * $per_page_record;     
        
     $query = "SELECT * FROM product LIMIT $start_from, $per_page_record";     
     $rs_result = mysqli_query ($conn, $query);  

?>

Display data

This section is very simple. In this section, we iterate the loop over the records that we fetched and display each record stored in columns of the table.

<?php  

  while ($row = mysqli_fetch_array($rs_result)) {    
        // Display each field of the records.    
  ?>     
  <tr>     
    <td><?php echo $row["id"]; ?></td>     
    <td><?php echo $row["product_name"]; ?></td>   
    <td><?php echo $row["product_price"]; ?></td>   
    <td><?php echo $row["product_category"]; ?></td>   
    <td><?php echo $row["product_details"]; ?></td>   
    <td><?php echo $row["product_stock"]; ?></td>                                           
</tr>     
  <?php     
  };  

?>

Pagination Link creation

Now the most important code is pagination link creation. So, we will create the Previous, Next, and numeric links for pagination and add them to bottom of the table.

<?php  

    if($page>=2) {   
        echo "<a href='index1.php?page=".($page-1)."'>  Prev </a>";   
    }       
                       
    for ($i=1; $i<=$total_pages; $i++) {   
            if ($i == $page) {   
                  $pagLink .= "<a class = 'active' href='index1.php?page="  
                                                    .$i."'>".$i." </a>";   
              }               
              else  {   
                  $pagLink .= "<a href='index1.php?page=".$i."'>   
                                                    ".$i." </a>";     
              }   
    };     
    echo $pagLink;   
      
    if($page<$total_pages){   
              echo "<a href='index1.php?page=".($page+1)."'>  Next </a>";   
    }   

?>

Code for Random Moment

In case when the number of pages is too much, this code helps us for random moment. By entering the page number in the input field, a user can directly move to that page. This code is written in JavaScript.

<?php  

    function go2Page()   
    {   
            var page = document.getElementById("page").value;   
            page = ((page><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((page<1)?1:page));   
            window.location.href = 'index1.php?page='+page;   
    }    

?>

Final Code

File: Index1.php
<?php  

  <html>   
  <head>   
    <title>How To Create Pagination In PHP and Mysql - itwebtuts</title>   
    <link rel="stylesheet"  
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">   
    <style>   
    table {  
        border-collapse: collapse;  
    }  
        .inline{   
            display: inline-block;   
            float: right;   
            margin: 20px 0px;   
        }   
         
        input, button{   
            height: 34px;   
        }   
  
    .pagination {   
        display: inline-block;   
    }   
    .pagination a {   
        font-weight:bold;   
        font-size:18px;   
        color: black;   
        float: left;   
        padding: 8px 16px;   
        text-decoration: none;   
        border:1px solid black;   
    }   
    .pagination a.active {   
            background-color: skyblue ;   
    }   
    .pagination a:hover:not(.active) {   
        background-color: pink;   
    }   
        </style>   
  </head>   
  <body>   
  <center>  
    <?php  
      
    // Import the file where we defined the connection to Database.     
        require_once "connection.php";   
    
        $per_page_record = 4;  // Number of entries to show in a page.   
        // Look for a GET variable page if not found default is 1.        
        if (isset($_GET["page"])) {    
            $page  = $_GET["page"];    
        }    
        else {    
          $page=1;    
        }    
    
        $start_from = ($page-1) * $per_page_record;     
    
        $query = "SELECT * FROM product LIMIT $start_from, $per_page_record";     
        $rs_result = mysqli_query ($conn, $query);    
    ?>    
  
    <div class="container">   
      <br>   
      <div>   
        <h1>Pagination Simple Example - itwebtuts</h1>   
          
        <table class="table table-striped table-condensed    
                                          table-bordered">   
          <thead>   
            <tr>   
              <th width="10%">ID</th>   
              <th>Name</th>   
              <th>price</th>   
              <th>category</th>   
              <th>details</th>   
              <th>stock</th>   
            </tr>   
          </thead>   
          <tbody>   
    <?php     
            while ($row = mysqli_fetch_array($rs_result)) {    
                  // Display each field of the records.    
            ?>     
            <tr>     
                <td><?php echo $row["id"]; ?></td>     
                <td><?php echo $row["product_name"]; ?></td>   
                <td><?php echo $row["product_price"]; ?></td>   
                <td><?php echo $row["product_category"]; ?></td>   
                <td><?php echo $row["product_details"]; ?></td>   
                <td><?php echo $row["product_stock"]; ?></td>                                           
            </tr>     
            <?php     
                };    
            ?>     
          </tbody>   
        </table>   
  
     <div class="pagination">    
      <?php  
        $query = "SELECT COUNT(*) FROM product";     
        $rs_result = mysqli_query($conn, $query);     
        $row = mysqli_fetch_row($rs_result);     
        $total_records = $row[0];     
          
    echo "</br>";     
        // Number of pages required.   
        $total_pages = ceil($total_records / $per_page_record);     
        $pagLink = "";       
      
        if($page>=2){   
            echo "<a href='index1.php?page=".($page-1)."'>  Prev </a>";   
        }       
                   
        for ($i=1; $i<=$total_pages; $i++) {   
          if ($i == $page) {   
              $pagLink .= "<a class = 'active' href='index1.php?page="  
                                                .$i."'>".$i." </a>";   
          }               
          else  {   
              $pagLink .= "<a href='index1.php?page=".$i."'>   
                                                ".$i." </a>";     
          }   
        };     
        echo $pagLink;   
  
        if($page<$total_pages){   
            echo "<a href='index1.php?page=".($page+1)."'>  Next </a>";   
        }   
  
      ?>    
      </div>  
  
  
      <div class="inline">   
      <input id="page" type="number" min="1" max="<?php echo $total_pages?>"   
      placeholder="<?php echo $page."/".$total_pages; ?>" required>   
      <button class="btn btn-success" onClick="go2Page();">Go</button>   
     </div>    
    </div>   
  </div>  
</center>   
  <script>   
    function go2Page()   
    {   
        var page = document.getElementById("page").value;   
        page = ((page><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((page<1)?1:page));   
        window.location.href = 'index1.php?page='+page;   
    }   
  </script>  
  </body>   
</html>

?>

I Will help you.

Laravel 8 Install in Ubuntu Tutorial

Hi Guys

Today,I will explain you how to install laravel 8 on ubuntu. we will show step by step install laravel 8 on ubuntu 16.04 18.04 and 20.00 .I will first install composer on upbantu.

Here, I will give you full example for laravel 8 install in ubuntu example as bellow.

Step 1: Install Composer

In this step,We will download the composer using the below command.

sudo apt-get update
sudo apt-get install curl
sudo curl -s https://getcomposer.org/installer | php

Now we move the composer.phar file into the bin folder and set the permission for all users.

sudo mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
Step 2: Install Laravel 8 Now this step, I will move on root directory “/var/www/html” and .download and install fresh laravel.
cd /var/www/html
composer create-project laravel/laravel blog --prefer-dist "8.*"
After installation laravel 8, we need to permission for the new directory. so we will set permission using the below command.
sudo chown -R www-data:www-data /var/www/html/blog/
sudo chmod -R 755 /var/www/html/blog/
Step 3: Configure Apache2 Here this step, we will configure the Apache2 site configuration file for Laravel. Run the below command to create a new configuration file. like laravel.conf
sudo nano /etc/apache2/sites-available/laravel.conf
After creating a file, copy and paste below the code in this file and save it.
<VirtualHost *:80>   
  ServerAdmin admin@example.com
     DocumentRoot /var/www/html/blog/public
     ServerName example.com

     <Directory /var/www/html/blog/public>
        Options +FollowSymlinks
        AllowOverride All
        Require all granted
     </Directory>

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Enable Laravel virtual host site and Apache2 Rewrite Module After the configuring Apache2 server. We will need to enable laravel virtual host site and Apache2 rewrite module. so we will enable using the below command.
sudo a2ensite laravel.conf
sudo a2enmod rewrite
Step 4: Restart Apache2 server Step 4: Restart Apache2 server Now the follow all the above changes. We will need to restart Apache2 using the below command.
sudo service apache2 restart
Step 5: Run Our Laravel Application last in this step, we will run our example using the below Url in the browser.
http://example.com
It will help you...

Laravel 8 Send Email Example Tutorial

step by step laravel 8 send email example

Hi Guys,

In this blog,I will learn you how to send example in laravel 8.we will show step by step laravel 8 send email example. you can easliy create laravel 8 send email example.

Laravel 8 provide several way to send email. You can also use core PHP method for send mail and you can also use some email service providers such as sendmail, smtp, mandrill, mailgun, mail, gmail etc. So you can choese any one and set configration. Laravel 8 provide Mail facade for mail send that have sevaral method for send email.In this example i going to show you how to send emails from gmail account example.

This example is very simple you can use as requirement easily. It is very simple to configration with gmail account so first open your .env file and add bellow gmail configration.

Here, I will give you full example for send email using Laravel 8 as bellow.

Step 1: .env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=dharmiktank128@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls
Step 2:Create Route Next,I am ready to send mail for test so first create test route for email sending. app/Http/routes.php
<?php

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

/*
|--------------------------------------------------------------------------
| 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('/send-mail', [SendMailController::class, 'index'])->name('send.mail.index');
Step 3: Controller

Here, We are add mail function in SendMailController.php file so add this way.

<?php

namespace App\Http\Controllers;

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

class SendMailController extends Controller
{
    public function index()
    {
      $user = User::find(1)->toArray();
      
      Mail::send('mail', $user, function($message) use ($user) {
          $message->to($user['email']);
          $message->subject('Welcome Mail');
      });

      dd('Mail Send Successfully');
    }
}
Step 3: Cretae View

At last create email template file for send mail so let's create mail.blade.php file in emials folder.

resources/views/emails/mailExample.blade.php
Hi {{ $name }}, How are you ?.

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/send-mail

It Will help you...

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