React Native Modal Popup Tutorial

React Native Modal Popup Tutorial

Hi dev,

Today, I will learn you how to create modal popup in react native. You can easily create modal in react native. First i will import namespace Modal, after I will make modal using modalVisible method in react native.

Here, I will give you full example for simply display modal using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init Modal 
Step 2 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from "react";
import { Alert,Modal,StyleSheet,Text,TouchableHighlight,View ,Header } from "react-native";

class App extends Component {
  state = {
    modalVisible: false
  };

  setModalVisible = (visible) => {
    this.setState({ modalVisible: visible });
  }

  render() {
    const { modalVisible } = this.state;
    return (
      <View style={styles.view}>
        <Text style={styles.header}>React Native Modal Popup Example  itwebtuts.com</Text>
        <Modal
          transparent={true}
          visible={modalVisible}
          onRequestClose={() => {
            Alert.alert("Modal has been closed.");
          }}
        >
          <View style={styles.view}>
            <View style={styles.modalView}>
              <Text style={styles.modalText}>Hii Friends!</Text>

              <TouchableHighlight
                style={{ ...styles.openButton, backgroundColor: "#2196F3" }}
                onPress={() => {
                  this.setModalVisible(!modalVisible);
                }}
              >
                <Text style={styles.textStyle}>Hide Modal</Text>
              </TouchableHighlight>
            </View>
          </View>
        </Modal>

        <TouchableHighlight
          style={styles.openButton}
          onPress={() => {
            this.setModalVisible(true);
          }}
        >
          <Text style={styles.textStyle}>Show Modal</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  view: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 0
  },
  modalView: {
    margin: 30,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 5
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5
  },
  openButton: {
    backgroundColor: "#115454",
    borderRadius: 5,
    padding: 15,
    elevation: 2
  },
  textStyle: {
    color: "white",
    textAlign: "center",
  },
  modalText: {
    marginBottom: 15,
  },
  header:{
    textAlign: 'center',
    fontSize: 20,
    marginBottom: 50,
  }
});

export default App; 
Step 3 - Run project

In the last step run your project using bellow command.

npm start
It will help you..

Jquery Responsive Multi-Level Menu Tutorial

Jquery Responsive Multi-Level Menu Tutorial

Hi Dev

Today, I will learn you how to create jquery responsive multi-level menu example. I will make of responsive multi-level menu using jquery example. We will create jquery responsive multi-level menu using dlmenu.you can click menu list on to open submenu list.

Here, I will give you full example for simply display responsive multi-level menu using jquery example. as bellow.

Example
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Multi-Level Menu Using Jquery Example</title>
    <link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="https://www.jqueryscript.net/demo/jQuery-Responsive-Multi-Level-Menu-Plugin-Dlmenu/css/default.css" />
    <link rel="stylesheet" type="text/css" href="https://www.jqueryscript.net/demo/jQuery-Responsive-Multi-Level-Menu-Plugin-Dlmenu/css/component.css"/>
    <script src="https://www.jqueryscript.net/demo/jQuery-Responsive-Multi-Level-Menu-Plugin-Dlmenu/js/modernizr.custom.js"></script>
</head>
<style type="text/css">
    .main-section ,.main,.column{
        margin:0px !important;
    }
</style>
<body>
<div class="container demo-1 main-section"> 
    <div class="main clearfix">
        <div class="column">
            <div id="dl-menu" class="dl-menuwrapper">
                <button>Open Menu</button>
                <ul class="dl-menu">
                    <li> <a href="#">Fashion</a>
                        <ul class="dl-submenu">
                            <li class="dl-back"><a href="#"> back</a></li>
                            <li> <a href="#">Men</a>
                                <ul class="dl-submenu">
                                    <li class="dl-back"><a href="#">back</a></li>
                                    <li><a href="#">Shirts</a></li>
                                    <li><a href="#">Jackets</a></li>
                                    <li><a href="#">Chinos & Trousers</a></li>
                                    <li><a href="#">Jeans</a></li>
                                    <li><a href="#">T-Shirts</a></li>
                                    <li><a href="#">Underwear</a></li>
                                </ul>
                            </li>
                            <li> <a href="#">Women</a>
                                <ul class="dl-submenu">
                                    <li class="dl-back"><a href="#">back</a></li>
                                    <li><a href="#">Jackets</a></li>
                                    <li><a href="#">Knits</a></li>
                                    <li><a href="#">Jeans</a></li>
                                    <li><a href="#">Dresses</a></li>
                                    <li><a href="#">Blouses</a></li>
                                    <li><a href="#">T-Shirts</a></li>
                                    <li><a href="#">Underwear</a></li>
                                </ul>
                            </li>
                            <li> <a href="#">Children</a>
                                <ul class="dl-submenu">
                                    <li class="dl-back"><a href="#">back</a></li>
                                    <li><a href="#">Boys</a></li>
                                    <li><a href="#">Girls</a></li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                    <li> <a href="#">Electronics</a>
                        <ul class="dl-submenu">
                            <li class="dl-back"><a href="#">back</a></li>
                            <li><a href="#">Camera & Photo</a></li>
                            <li><a href="#">TV & Home Cinema</a></li>
                            <li><a href="#">Phones</a></li>
                            <li><a href="#">PC & Video Games</a></li>
                        </ul>
                    </li>
                    <li> <a href="#">Furniture</a>
                        <ul class="dl-submenu">
                            <li class="dl-back"><a href="#">back</a></li>
                            <li> <a href="#">Living Room</a>
                                <ul class="dl-submenu">
                                    <li class="dl-back"><a href="#">back</a></li>
                                    <li><a href="#">Sofas & Loveseats</a></li>
                                    <li><a href="#">Coffee & Accent Tables</a></li>
                                    <li><a href="#">Chairs & Recliners</a></li>
                                    <li><a href="#">Bookshelves</a></li>
                                </ul>
                            </li>
                            <li> <a href="#">Bedroom</a>
                                <ul class="dl-submenu">
                                <li class="dl-back"><a href="#">back</a></li>
                                <li> <a href="#">Beds</a>
                                    <ul class="dl-submenu">
                                        <li class="dl-back"><a href="#">back</a></li>
                                        <li><a href="#">Upholstered Beds</a></li>
                                        <li><a href="#">Divans</a></li>
                                        <li><a href="#">Metal Beds</a></li>
                                        <li><a href="#">Storage Beds</a></li>
                                        <li><a href="#">Wooden Beds</a></li>
                                        <li><a href="#">Children's Beds</a></li>
                                    </ul>
                                </li>
                                <li><a href="#">Bedroom Sets</a></li>
                                <li><a href="#">Chests & Dressers</a></li>
                                </ul>
                            </li>
                            <li><a href="#">Home Office</a></li>
                            <li><a href="#">Dining & Bar</a></li>
                            <li><a href="#">Patio</a></li>
                        </ul>
                    </li>
                    <li> <a href="#">Jewelry & Watches</a>
                        <ul class="dl-submenu">
                            <li class="dl-back"><a href="#">back</a></li>
                            <li><a href="#">Fine Jewelry</a></li>
                            <li><a href="#">Fashion Jewelry</a></li>
                            <li><a href="#">Watches</a></li>
                            <li> <a href="#">Wedding Jewelry</a>
                                <ul class="dl-submenu">
                                    <li class="dl-back"><a href="#">back</a></li>
                                    <li><a href="#">Engagement Rings</a></li>
                                    <li><a href="#">Bridal Sets</a></li>
                                    <li><a href="#">Women's Wedding Bands</a></li>
                                    <li><a href="#">Men's Wedding Bands</a></li>
                                </ul>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script src="https://www.jqueryscript.net/demo/jQuery-Responsive-Multi-Level-Menu-Plugin-Dlmenu/js/jquery.dlmenu.js"></script> 
<script>
	$(function() {
		$('#dl-menu').dlmenu();
	});
</script>
</html>

It Will help you..

Laravel Queue Example Tutorial

Laravel Queue Example Tutorial

Hi Guys

Today, I will learn how to end email using queue in laravel. we will create email send using queue in this example.We will show how to use queue jobs in laravel from scratch.

When you send email for verification or send invoice then it load time to send mail because it is services. you see some process take time to load like email send, payment gateway etc.If you don't want to wait to user for send email or other process on loading server side process then you can use queue. because it's very fast and visitor will happy to see loading time.

In this example, I will very simple example to create queue with database driver for test email sending.You can definitely understand how to work queue and how it's easy. If you haven't used before then don't worry, here if from starch and very simple.

Here,I give you full example of Queue example step by step like create laravel project,mail,balde,job file etc. So you have to just follow few steps.

Step 1 : Install Laravel 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: Create Mail Setup

Now this step, We are going from scratch and in first step, we will create email for testing using Laravel Mail facade. So let's simple run bellow command

php artisan make:mail SendEmailTest
After you will have new folder "Mail" in app directory with SendEmailTest.php file. So let's simply copy bellow code and past on that file.
following path:/app/Mail/SendEmailTest.php
<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
  
class SendEmailTest extends Mailable
{
    use Queueable, SerializesModels;
  
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
          
    }
  
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.test');
    }
}

Now we require to create email view using blade file. So we will create simple view file and copy bellow code om following path.

following path:/resources/views/emails/test.blade.php
<!DOCTYPE html>
<html>
    <head>
    	<title>Laravel Queue Example Tutorial - itwebtuts.blogspot.com</title>
</head>
<body>
    <center>
        <h2>
            Laravel Queue Example Tutorial - itwebtuts.blogspot.com
        </h2>
    </center>
    <p>Hi, Sir</p>
    <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>
    <h5>Thank you Sir. :)</h5>
</body>
</html>
Here configuration of view file, we have to setup for email send, So let' set configuration in .env file:
following path: .env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=xyz@gmail.com
MAIL_PASSWORD=123456
MAIL_ENCRYPTION=tls
Step 3: Configuration of Queue

Now In step, we will make configuration on queue driver so first of all, we will set queue driver "database". You can set as you want also we will define driver as redis too. So here define database driver on ".env" file:

following path: .env
QUEUE_CONNECTION=database

After that we need to generate migration and create tables for queue. So let's run bellow command for queue database tables:

Generate Migration:
php artisan queue:table
Run Migration:
php artisan migrate
Step 4: Create Queue Job

Here we will create queue job bey following command, this command will create queue job file with Queueable. So let's run bellow command:

php artisan make:job SendEmailJob

After you have SendEmailJob.php file in "Jobs" directory. So let's see that file and put bellow code on that file.

following path: /app/Jobs/SendEmailJob.php
<?php
  
namespace App\Jobs;
   
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Mail\SendEmailTest;
use Mail;
   
class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  
    protected $details;
  
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($details)
    {
        $this->details = $details;
    }
   
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $email = new SendEmailTest();
        Mail::to($this->details['email'])->send($email);
    }
}
Step 5: Test Queue Job

Here In this step use and test created queue job, so let's simple create route with following code for testing created queue.

following path: /routes/web.php
Route::get('email-test', function(){
  
	$details['email'] = 'your_email@gmail.com';
  
    dispatch(new App\Jobs\SendEmailJob($details));
  
    dd('done');
});

After, you can watch your queue process using laravel queue command, so let's run bellow command:

php artisan queue:listen

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

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/email-test

It will help you...

PHP Crop Image Before Upload using Cropper JS Example

PHP Crop Image Before Upload using Cropper JS Example

Hi Guys,

Today, you will give Php cropper js example. this example will help you Php crop image before upload. This tutorial will give you simple example of crop image using cropper.js Php. you will learn Php crop image before upload cropper.js. Let's see bellow example cropper js Php example.

Cropper.js is an easy to use JavaScript/jQuery plugin for image cropping with support of live previews and custom aspect ratio.this plugin provide features move,zoom,rotate,Fully responsive and mobile-friendly.

We will use model view in example. model display to upload image and crop image preview.follow bellow step example.

Example :

index.html

<!DOCTYPE html>
<html>
<head>
        <title>PHP Crop Image Before Upload using Cropper JS</title>
        <meta name="_token" content="{{ csrf_token() }}">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha256-WqU1JavFxSAMcLP2WIOI+GB2zWmShMI82mTpLDcqFUg=" crossorigin="anonymous"></script>
        <link rel="stylesheet"  href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" integrity="sha256-jKV9n9bkk/CTP8zbtEtnKaKf+ehRovOYeKoyfthwbC8=" crossorigin="anonymous" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js" integrity="sha256-CgvH7sz3tHhkiVKh05kSUgG97YtzYNnWt6OXcmYzqHY=" crossorigin="anonymous"></script>
    </head>
    <style type="text/css">
    img {
      display: block;
      max-width: 100%;
    }
    .preview {
      overflow: hidden;
      width: 160px; 
      height: 160px;
      margin: 10px;
      border: 1px solid red;
    }
    .modal-lg{
      max-width: 1000px !important;
    }
    </style>
    <body>
    <div class="container mt-5">
        <h2>PHP Crop Image Before Upload using Cropper JS - MyWebtuts.com</h2>
        <form method="post">
        <div class="custom-file">
        <input type="file" class="custom-file-input image" id="customFile" name="image">
        <label class="custom-file-label" for="customFile">Choose Images</label>
      </div>
        </form>
    </div>

    <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="modalLabel">PHP Crop Image Before Upload using Cropper JS - MyWebtuts.com</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="img-container">
                <div class="row">
                    <div class="col-md-8">
                        <img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
                    </div>
                    <div class="col-md-4">
                        <div class="preview"></div>
                    </div>
                </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" id="crop">Crop</button>
          </div>
        </div>
      </div>
    </div>

    </div>
    </div>
    <script>

    // Add the following code if you want the name of the file appear on select
    $(".custom-file-input").on("change", function() {
      var fileName = $(this).val().split("\\").pop();
      $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
    });

    var $modal = $('#modal');
    var image = document.getElementById('image');
    var cropper;
      
    $("body").on("change", ".image", function(e){
        var files = e.target.files;
        var done = function (url) {
          image.src = url;
          $modal.modal('show');
        };
        var reader;
        var file;
        var url;

        if (files && files.length > 0) {
          file = files[0];

          if (URL) {
            done(URL.createObjectURL(file));
          } else if (FileReader) {
            reader = new FileReader();
            reader.onload = function (e) {
              done(reader.result);
            };
            reader.readAsDataURL(file);
          }
        }
    });

    $modal.on('shown.bs.modal', function () {
        cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 3,
        preview: '.preview'
        });
    }).on('hidden.bs.modal', function () {
       cropper.destroy();
       cropper = null;
    });

    $("#crop").click(function(){
        canvas = cropper.getCroppedCanvas({
          width: 160,
          height: 160,
        });

        canvas.toBlob(function(blob) {
            url = URL.createObjectURL(blob);
            var reader = new FileReader();
             reader.readAsDataURL(blob); 
             reader.onloadend = function() {
                var base64data = reader.result;  
                
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "upload.php",
                    data: {image: base64data},
                    success: function(data){
                        console.log(data);
                        $modal.modal('hide');
                        alert("success upload image");
                    }
                  });
             }
        });
    })

    </script>
    </body>
    </html>

upload.php

<?php

    $folderPath = 'uploads/';

    $image_parts = explode(";base64,", $_POST['image']);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $file = $folderPath . uniqid() . '.png';

    file_put_contents($file, $image_base64);

    echo json_encode(["image uploaded successfully."]);

?>

You will create to upload folder in root directory

I will help you..

PHP Mysql CRUD Operation Example

CRUD(Create, Read, Update, and Delete)

Hi Guys,

Today, In this tutorial you'll give how to build a CRUD application with PHP and MySQL.

What is CRUD

CRUD(Create, Read, Update, and Delete) is an acronym for Create, Read, Update, and Delete. CRUD operations are simply data manipulation for database.In this tutorial we'll create a simple PHP application to perform all these operations on a MySQL database table at one place.

Creating the Database Table

Execute the following SQL query to create a table named users inside your MySQL database. We will use this table for all of our future operations.

CREATE TABLE users (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    fullname VARCHAR(100) NOT NULL,
    email VARCHAR(255) NOT NULL,
    salary INT(10) NOT NULL
);

Creating the Config File

Database Configuration config.php
<?php

    /* Database credentials. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'root');
    define('DB_PASSWORD', 'root');
    define('DB_NAME', 'php_curd');
     
    /* Attempt to connect to MySQL database */
    $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
     
    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

?>

Create a file named "index.php" and put the following code in it:

index.php
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();   
        });
    </script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="mt-5 mb-3 clearfix">
                    <h2 class="pull-left">users Details</h2>
                    <a href="create.php" class="btn btn-success pull-right"><i class="fa fa-plus"></i></a>
                </div>
                <?php
                // Include config file
                require_once "config.php";
                
                // Attempt select query execution
                $sql = "SELECT * FROM users";
                if($result = mysqli_query($link, $sql)){
                    if(mysqli_num_rows($result) > 0){
                        echo '<table class="table table-bordered table-striped">';
                            echo "<thead>";
                                echo "<tr class='bg-dark text-white'>";
                                    echo "<th>#</th>";
                                    echo "<th>FullName</th>";
                                    echo "<th>Email</th>";
                                    echo "<th>Salary</th>";
                                    echo "<th width='22%'>Action</th>";
                                echo "</tr>";
                            echo "</thead>";
                            echo "<tbody>";
                            while($row = mysqli_fetch_array($result)){
                                echo "<tr>";
                                    echo "<td>" . $row['id'] . "</td>";
                                    echo "<td>" . $row['fullname'] . "</td>";
                                    echo "<td>" . $row['email'] . "</td>";
                                    echo "<td>" . $row['salary'] . "</td>";
                                    echo "<td>";
                                        echo '<a href="show.php?id='. $row['id'] .'" class="mr-3 btn btn-success" title="View Record" data-toggle="tooltip"><span class="fa fa-eye"></span></a>';
                                        echo '<a href="update.php?id='. $row['id'] .'" class="mr-3 btn btn-primary" title="Update Record" data-toggle="tooltip"><span class="fa fa-pencil"></span></a>';
                                        echo '<a href="delete.php?id='. $row['id'] .'" title="Delete Record" class="mr-3 btn btn-danger" data-toggle="tooltip"><span class="fa fa-trash"></span></a>';
                                    echo "</td>";
                                echo "</tr>";
                            }
                            echo "</tbody>";                            
                        echo "</table>";
                        // Free result set
                        mysqli_free_result($result);
                    } else{
                        echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
                    }
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }

                // Close connection
                mysqli_close($link);
                ?>
            </div>
        </div>        
    </div>
</body>
</html>

Creating the Create Page

In this section we'll build the Create functionality of our CRUD application.

Now, Let's create a file named "create.php" and put the following code inside it. It will generate a web form that can be used to insert records in the users table.

create.php
<?php

    // Include config file
    require_once "config.php";
     
    // Define variables and initialize with empty values
    $name = $email = $salary = "";
    $name_err = $email_err = $salary_err = "";
     
    // Processing form data when form is submitted
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        // Validate name
        $input_name = trim($_POST["fullname"]);
        if(empty($input_name)){
            $name_err = "Please enter a name.";
        } elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
            $name_err = "Please enter a valid name.";
        } else{
            $name = $input_name;
        }
        
        // Validate address
        $input_email = trim($_POST["email"]);
        if(empty($input_email)){
            $email_err = "Please enter an Email.";     
        } else{
            $email = $input_email;
        }
        
        // Validate salary
        $input_salary = trim($_POST["salary"]);
        if(empty($input_salary)){
            $salary_err = "Please enter the salary amount.";     
        } elseif(!ctype_digit($input_salary)){
            $salary_err = "Please enter a positive integer value.";
        } else{
            $salary = $input_salary;
        }
        
        // Check input errors before inserting in database
        if(empty($name_err) && empty($email_err) && empty($salary_err)){
            // Prepare an insert statement
            $sql = "INSERT INTO users (fullname, email, salary) VALUES (?, ?, ?)";
             
            if($stmt = mysqli_prepare($link, $sql)){
                // Bind variables to the prepared statement as parameters
                mysqli_stmt_bind_param($stmt, "sss", $param_name, $param_email, $param_salary);
                
                // Set parameters
                $param_name = $name;
                $param_email = $email;
                $param_salary = $salary;
                
                // Attempt to execute the prepared statement
                if(mysqli_stmt_execute($stmt)){
                    // Records created successfully. Redirect to landing page
                    header("location: index.php");
                    exit();
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }
            }
             
            // Close statement
            mysqli_stmt_close($stmt);
        }
        
        // Close connection
        mysqli_close($link);
    }

?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-5 mx-auto">
                <div class="card">
                    <div class="card-header bg-warning">
                        <h2 class="">Create Record</h2>
                    </div>
                    <div class="card-body">
                        <p>Please fill this form and submit to add user record to the database.</p>
                        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                            <div class="form-group">
                                <label>FullName</label>
                                <input type="text" name="fullname" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
                                <span class="invalid-feedback"><?php echo $name_err;?></span>
                            </div>
                            <div class="form-group">
                                  <label>Email</label>
                                <input type="email" name="email" class="form-control <?php echo (!empty($email_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $email; ?>">
                                <span class="invalid-feedback"><?php echo $email_err;?></span>
                            </div>
                            <div class="form-group">
                                <label>Salary</label>
                                <input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
                                <span class="invalid-feedback"><?php echo $salary_err;?></span>
                            </div>
                            <input type="submit" class="btn btn-primary" value="Submit">
                            <a href="index.php" class="btn btn-secondary ml-2">Cancel</a>
                        </form>
                    </div>
                </div>
            </div>
        </div>        
    </div>
</body>
</html>

Show Data

Now it's time to build the Read functionality of our CRUD application.

Now, Let's create a file named "show.php" and put the following code inside it. It will simply retrieve the records from the users table based the id attribute of the user.

show.php

<?php

    // Check existence of id parameter before processing further
    if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
        // Include config file
        require_once "config.php";
        
        // Prepare a select statement
        $sql = "SELECT * FROM users WHERE id = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "i", $param_id);
            
            // Set pg_parameter_status()
            $param_id = trim($_GET["id"]);
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                $result = mysqli_stmt_get_result($stmt);
        
                if(mysqli_num_rows($result) == 1){
                    /* Fetch result row as an associative array. Since the result set
                    contains only one row, we don't need to use while loop */
                    $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                    
                    // Retrieve individual field value
                    $name = $row["fullname"];
                    $address = $row["email"];
                    $salary = $row["salary"];
                } else{
                    // URL doesn't contain valid id parameter. Redirect to error page
                    header("location: error.php");
                    exit();
                }
                
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        mysqli_stmt_close($stmt);
        
        // Close connection
        mysqli_close($link);
    } else{
        // URL doesn't contain id parameter. Redirect to error page
        header("location: error.php");
        exit();
    }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h1 class="mt-5 mb-3">View Record</h1>
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th width="10%">FullName</th>
                            <td><?php echo $row["fullname"]; ?></td>
                        </tr>
                        <tr>
                            <th width="10%">Email</th>
                            <td><?php echo $row["email"]; ?></td>
                        </tr>
                        <tr>
                            <th width="10%">Salary</th>
                            <td><?php echo $row["salary"]; ?></td>
                        </tr>
                    </thead>
                </table>
                <p><a href="index.php" class="btn btn-primary">Back</a></p>
            </div>
        </div>        
    </div>
</body>
</html>
Creating the Update Page

Similarly, we can build the Update functionality of our CRUD application.

Now, Let's create a file named "update.php" and put the following code inside it. It will update the existing records in the users table based the id attribute of the user.

update.php

<?php

    // Include config file
    require_once "config.php";
     
    // Define variables and initialize with empty values
    $name = $email = $salary = "";
    $name_err = $email_err = $salary_err = "";
     
    // Processing form data when form is submitted
    if(isset($_POST["id"]) && !empty($_POST["id"])){
        // Get hidden input value
        $id = $_POST["id"];
        
        // Validate name
        $input_name = trim($_POST["fullname"]);
        if(empty($input_name)){
            $name_err = "Please enter a name.";
        } elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
            $name_err = "Please enter a valid name.";
        } else{
            $name = $input_name;
        }
        
        // Validate address address
        $input_email = trim($_POST["email"]);
        if(empty($input_email)){
            $email_err = "Please enter an Email.";     
        } else{
            $email = $input_email;
        }
        
        // Validate salary
        $input_salary = trim($_POST["salary"]);
        if(empty($input_salary)){
            $salary_err = "Please enter the salary amount.";     
        } elseif(!ctype_digit($input_salary)){
            $salary_err = "Please enter a positive integer value.";
        } else{
            $salary = $input_salary;
        }
        
        // Check input errors before inserting in database
        if(empty($name_err) && empty($email_err) && empty($salary_err)){
            // Prepare an update statement
            $sql = "UPDATE users SET fullname=?, email=?, salary=? WHERE id=?";
             
            if($stmt = mysqli_prepare($link, $sql)){
                // Bind variables to the prepared statement as parameters
                mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_email, $param_salary, $param_id);
                
                // Set parameters
                $param_name = $name;
                $param_email = $email;
                $param_salary = $salary;
                $param_id = $id;
                
                // Attempt to execute the prepared statement
                if(mysqli_stmt_execute($stmt)){
                    // Records updated successfully. Redirect to landing page
                    header("location: index.php");
                    exit();
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }
            }
             
            // Close statement
            mysqli_stmt_close($stmt);
        }
        
        // Close connection
        mysqli_close($link);
    } else{
        // Check existence of id parameter before processing further
        if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
            // Get URL parameter
            $id =  trim($_GET["id"]);
            
            // Prepare a select statement
            $sql = "SELECT * FROM users WHERE id = ?";
            if($stmt = mysqli_prepare($link, $sql)){
                // Bind variables to the prepared statement as parameters
                mysqli_stmt_bind_param($stmt, "i", $param_id);
                
                // Set parameters
                $param_id = $id;
                
                // Attempt to execute the prepared statement
                if(mysqli_stmt_execute($stmt)){
                    $result = mysqli_stmt_get_result($stmt);
        
                    if(mysqli_num_rows($result) == 1){
                        /* Fetch result row as an associative array. Since the result set
                        contains only one row, we don't need to use while loop */
                        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                        
                        // Retrieve individual field value
                        $name = $row["fullname"];
                        $email = $row["email"];
                        $salary = $row["salary"];
                    } else{
                        // URL doesn't contain valid id. Redirect to error page
                        header("location: error.php");
                        exit();
                    }
                    
                } else{
                    echo "Oops! Something went wrong. Please try again later.";
                }
            }
            
            // Close statement
            mysqli_stmt_close($stmt);
            
            // Close connection
            mysqli_close($link);
        }  else{
            // URL doesn't contain id parameter. Redirect to error page
            header("location: error.php");
            exit();
        }
    }
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Update Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-5 mx-auto">
                <div class="card">
                    <div class="card-header bg-warning">
                        <h2 class="">Update Record</h2>
                    </div>
                    <div class="card-body">
                        <p>Please edit the input values and submit to update the user record.</p>
                        <form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
                            <div class="form-group">
                                <label>Name</label>
                                <input type="text" name="fullname" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
                                <span class="invalid-feedback"><?php echo $name_err;?></span>
                            </div>
                            <div class="form-group">
                                <label>Email</label>
                                <input type="email" name="email" class="form-control <?php echo (!empty($email_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $email; ?>">
                                <span class="invalid-feedback"><?php echo $email_err;?></span>
                            </div>
                            <div class="form-group">
                                <label>Salary</label>
                                <input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
                                <span class="invalid-feedback"><?php echo $salary_err;?></span>
                            </div>
                            <input type="hidden" name="id" value="<?php echo $id; ?>"/>
                            <input type="submit" class="btn btn-primary" value="Submit">
                            <a href="index.php" class="btn btn-secondary ml-2">Cancel</a>
                        </form>
                    </div>
                </div>
            </div>
        </div>        
    </div>
</body>
</html>

Creating the Delete Page

Finally, we will build the Delete functionality of our CRUD application.

Now, Let's create a file named "delete.php" and put the following code inside it. It will delete the existing records from the users table based the id attribute of the user.

delete.php
<?php

    // Process delete operation after confirmation
    if(isset($_POST["id"]) && !empty($_POST["id"])){
        // Include config file
        require_once "config.php";
        
        // Prepare a delete statement
        $sql = "DELETE FROM users WHERE id = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "i", $param_id);
            
            // Set parameters
            $param_id = trim($_POST["id"]);
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Records deleted successfully. Redirect to landing page
                header("location: index.php");
                exit();
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
         
        // Close statement
        mysqli_stmt_close($stmt);
        
        // Close connection
        mysqli_close($link);
    } else{
        // Check existence of id parameter
        if(empty(trim($_GET["id"]))){
            // URL doesn't contain id parameter. Redirect to error page
            header("location: error.php");
            exit();
        }
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Delete Record</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .wrapper{
            width: 600px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <h2 class="mt-5 mb-3">Delete Record</h2>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <div class="alert alert-danger">
                            <input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
                            <p>Are you sure you want to delete this user record?</p>
                            <p>
                                <input type="submit" value="Yes" class="btn btn-danger">
                                <a href="index.php" class="btn btn-secondary">No</a>
                            </p>
                        </div>
                    </form>
                </div>
            </div>        
        </div>
    </div>
</body>
</html>

Creating the Error Page

At the end, let's create one more file "error.php". This page will be displayed if request is invalid i.e. if id parameter is missing from the URL query string or it is not valid.

error.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .wrapper{
            width: 600px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <h2 class="mt-5 mb-3">Invalid Request</h2>
                    <div class="alert alert-danger">Sorry, you've made an invalid request. Please <a href="index.php" class="alert-link">go back</a> and try again.</div>
                </div>
            </div>        
        </div>
    </div>
</body>
</html>

I will help you..

Laravel Many to Many Eloquent Relationship Tutorial

Hi Dev,

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

We will create "user" ,"role_user" and "role" table.both table are connected with each other, I will create Many 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. Many to Many Relationship use "belongsToMany()" for relation.

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

Step:1 Create Migration

In this step, we will need two tables in our database user ,role_user and role. I will start to create the model and migrations, then we will define the Many to many to Many relationship.To generate models and migrations, run below two commands in your terminal.

php artisan make:model User -m

php artisan make:model RoleUser -m

php artisan make:model Role -m

Above command will generate two models in your app folder called user and role. 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_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

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

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

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

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

Now run the below command to create user and role tables in your database:

php artisan migrate
Step:2 Create Model Relationship

Now in this step, we have user ,role_user and role tables ready, let’s define the Many to manMany relationship in our models. our app\user.php model file and add a new function called roles() which will return a many to Many relationship like below:

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

class user extends Model
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_users');
    }
}

you can see, in the roles() method we are defining a Many to Many relationship on role model.

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

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

class Role extends Model
{
   /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    Protected $fillable=[
        'name'
    ];
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    public function users()
    {
        return $this->belongsToMany(User::class, 'role_users');
    }
}

you can see, in the users() method we are defining a Many to Many relationship on role model.

app\RoleUser.php
<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class RoleUser extends Model
{   
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    public $table = 'role_user';
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */
    protected $fillable = [
        'user_id','role_id'
    ];
}
Step 3 : Insert Records

Let’s in this step add data to user and role from controller:

app\Http\Controllers\user.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Role;

class userController extends Controller
{
    public function createRecored()
    {      
       //create recored in user table
       $user = User::find(2);   
       $roleIds = [1, 2];
       $user->roles()->attach($roleIds);

       $user = User::find(3);   
       $roleIds = [1, 2];
       $user->roles()->sync($roleIds);

       //create recored in role table

       $role = Role::find(1);   
       $userIds = [10, 11];
       $role->users()->attach($userIds);

       $role = Role::find(2);   
       $userIds = [10, 11];
       $role->users()->sync($userIds);
    }
}
Step 4 : Retrieve Records

Now in this step retrieve records model

app\Http\Controllers\user.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Role;

class userController extends Controller
{
    public function retrieveRecords()
    {   
        //Retrieve recoed in user table
        $user = User::find(1);    
        dd($user->roles);
        
        //Retrieve recoed in role table
        $role = Role::find(1);  
        dd($role->users);
    }
}

it will help you....

Javascript File Size Validation Example

Javascript File Size Validation Example

Hi Dev,

Today, i will learn how to check file size validation using Javascript. we will check file size validation using Javascript. I can check file size validation using Javascript.Now, we get the file size on the image change event and after.

I will check the file size, if file size greater than 2mb then it will return the error messages otherwise return the success message.ill explain to you how to check file (Image) size validation before upload the file using Javascript.

solution
function OnFileValidation() {
    var image = document.getElementById("image");
    if (typeof (image.files) != "undefined") {
        var size = parseFloat(image.files[0].size / (1024 * 1024)).toFixed(2); 
        if(size > 2) {
            alert('Please select image size less than 2 MB');
        }else{
            alert('success');
        }
    } else {
        alert("This browser does not support HTML5.");
    }
}

So you can see here our example.

Example
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Javascript File Size Validation  Example</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css">
</head>
<body class="bg-dark">
    <div class="continer">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card">
                    <div class="card-header">
                        <h5>File Size Validation Using Javascript Example</h5>
                    </div>
                    <div class="card-body">
                        <form method="post" name="frmAdd" id="frmAdd">
                            <label for="image">Image:</label>
                            <input type="file" name="image" class="form-control" id="image" value="" onchange="OnFileValidation()"><br/>
                            <button type="submit" class="btn btn-success">Submit</button>        
                       </form>
                    </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="Javascript">
    function OnFileValidation() {
        var image = document.getElementById("image");
        if (typeof (image.files) != "undefined") {
            var size = parseFloat(image.files[0].size / (1024 * 1024)).toFixed(2); 
            if(size > 2) {
                alert('Please select image size less than 2 MB');
            }else{
                alert('success');
            }
        } else {
            alert("This browser does not support HTML5.");
        }
    }
</script>
</html>

It will help you....

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