Laravel IP Address Using Get Location Example

Laravel IP Address Using Get Location Example

Hi Dev,

Today,I will learn you how to get location useing ip address in laravel. we will show example of laravel ip address using get location. you can easy to get location useing ip address in laravel.In this example, I will useing stevebauman/location packege get location useing ip address in laravel.

Many time you will need to get visitor's details for security, spam prevention etc. It's very easy to get visitor ip address and their location in PHP Laravel.

Step 1: Install stevebauman/location

Now, We will install stevebauman/location package using below command.Require this package with composer. It is recommended to only require the package for development.

composer require stevebauman/location
Step 2: Add providers and aliases

In this step,We will add below providers and aliases in the "config/app.php" file.

config/app.php
'providers' => [
  ....
  Stevebauman\Location\LocationServiceProvider::class,
],
'aliases' => [
  ....
  'Location' => Stevebauman\Location\Facades\Location::class,
]
Step 3:config with the publish command

In this step,I will publish Stevebauman\Location\LocationServiceProvider package follwing command.

php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
Step 4: Route routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LocationController;
/*
|--------------------------------------------------------------------------
| 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('location',[LocationController::class,'index']);
Step 5:Controller : app/Http/Controllers/LocationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class LocationController extends Controller
{
  public function index(Request $request)
    {
      $ip= $request->ip();
      $data = \Location::get($ip);
      dd($data);
    }
}

Now we are ready to run our form laravel,laravel ip address using get location example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/location

You will see layout as like bellow:

OutPut
Stevebauman\Location\Position {#1479 
  +ip: "43.241.145.109"
  +countryName: "India"
  +countryCode: "IN"
  +regionCode: "GJ"
  +regionName: "Gujarat"
  +cityName: "Rajkot"
  +zipCode: "360004"
  +isoCode: null
  +postalCode: null
  +latitude: "22.2916"
  +longitude: "70.7932"
  +metroCode: null
  +areaCode: "GJ"
  +driver: "Stevebauman\Location\Drivers\IpApi"
}
It will help you....

React Native Flexbox Tutorial With Example

React Native Flexbox Example

Hi Dev,

Today, I will learn you how to create flexbox in react native. You can easily create flexbox in react native. First i will import namespace View, after I will make flexbox using View tag in react native.

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

Step 1 - Create project

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

expo init flexbox 
Step 2 - App.js

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

import React, { Component } from 'react'
import { View, StyleSheet } from 'react-native'

const Home = (props) => {
   return (
      <View style = {styles.container}>
         <View style = {styles.redbox} />
         <View style = {styles.greenbox} />
         <View style = {styles.corolbox} />
         <View style = {styles.purplebox} />
      </View>
   )
}

export default Home

const styles = StyleSheet.create ({
   container: {
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      paddingTop: 130
   },
   redbox: {
      width: 100,
      height: 100,
      backgroundColor: 'red'
   },
   corolbox: {
      width: 100,
      height: 100,
      backgroundColor: '#ff7f50'
   },
   greenbox: {
      width: 100,
      height: 100,
      backgroundColor: 'green'
   },
   purplebox: {
      width: 100,
      height: 100,
      backgroundColor: 'purple'
   }
})
Step 3 - Run project

In the last step run your project using bellow command.

expo start
It will help you...

Laravel Soft Delete Example Tutorial

Laravel Soft Delete Example Tutorial

Hi Guys,

Today , I will learn how to utilize soft efface in laravel,we are tell simple example of laravel soft expunge.it will laravel soft efface migration.we abstract row from database when efface record from site. But laravel introduce SoftDeletes in models that way we can't abstract from database but if abstract record from front side then it doesn't show record on front. So we can retrieve record from database if we abstract erroneous row.

How work soft efface, laravel integrate expunged_at column on the table that be default will be null and when we abstract then it will place current timestamp, Laravel Model always fetch that record have only expunged_at = null.

So, how to utilize in our project, so first when you engender table moigration then you have to integrate softDeletes(). you can optically discern like bellow example of migration.

Here i bellow example you can learn soft efface in laravel

Create Post Migration Soft Delete

In this post migration open Post migration file and put the below same code.

Path: /database/migrations/2020_01_02_095534_create_posts_table.php
<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->softDeletes();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Create Post Model Soft Delete

Next, go to app/Post.php and open post model file and put the below same code.

Now you can find deleted_at column in your post table and you have also model should look like as bellow

here following path of model fille

Path:/app/Post.php
<?php
namespace App;

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

class Post extends Model
{
    use SoftDeletes;

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

    /**
    * The attributes that should be mutated to dates.
    *
    * @var array
    */
    protected $dates = ['deleted_at'];
}
Get All Records

Now, you can use Post model as normally like you use before, you get all record like this way.

$data = Post::get();
Delete one Record

It will return all record that have deleted_at = null only and you can also remove record like this way:

$data = Post::find(1)->delete();
Get All Records After Delete one Record

Now, you can use Post model as normally like you use before, you get all record After Delete one Record like this way.

$data = Post::withTrashed()->get();

You can check the table records.

It will help you..

Bootstrap Datetimepicker Disable Weekends Example

Bootstrap Datetimepicker Disable Weekends Example

Bootstrap Datetimepicker Disable Weekends Example

Hi Dev,

Today,i will learn you simple example of Bootstrap datetimepicker disable weekends.you can disable bootstrap datetimepicker using daysOfWeekDisabled method.we are disabled bootstrap datetimepicker in weekends.it will useing daysOfWeekDisabled options to disable weekends in bootstrap datetimepicker.

Here following example of bootstrap datetimepicker disable weekends.

Solution
    $(function () {
        $('#datetimepicker1').datetimepicker({
            daysOfWeekDisabled: [0,6]
        });
    });
Example
<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Datetimepicker Disable Weekends Example</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body style="background:#e2e2e2;">
<div class="container">
    <h2>Bootstrap Datetimepicker Disable Weekends Example - nicesnippets.com</h2>
    <div class="row">
        <div class='col-sm-6'>
            <div class="form-group">
                <div class='input-group date' id='datetimepicker1'>
                    <input type='text' class="form-control" />
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            $(function () {
                $('#datetimepicker1').datetimepicker({
                    daysOfWeekDisabled: [0,6]
                });
            });
        </script>
    </div>
</div>
</body>
</html>

It will help you..

PHP Highcharts Column Chart Example

PHP Highcharts Column Chart Example

PHP Highcharts Column Chart Example

Hi Dev,

In this blog,I will learn you how to implement simple dynamic column highcharts utilizing php mysql database.We will show example of php highcharts column chart.Highcharts is a one type js library, that provide to populate bar chart, line chart, area chart, column chart etc. Highcharts library additionally provide several theme and graphic design that way you can make better layout. Highcharts is a very popular and simple library for php developer.

Here, I will give you full example for simply exhibit highcharts column chart utilizing php as bellow.

Step 1: Create Database

In first step we require to create new database "phpexample", Or you can rename as you like. After creating successfully database, In this example we will show compare column chart of viewer and clicks, So we require to create tables. we require following two tables.

1)test_viewer

2)test_click

In this step two table by following mysql query as like bellow example.

Create test_viewer table
CREATE TABLE IF NOT EXISTS `test_viewer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numberofview` int(11) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
Create test_click table:
CREATE TABLE IF NOT EXISTS `test_click` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numberofclick` int(12) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

Now we require to some dummy data with different year, So you can add like added bellow screen shot, I added both tables with some dummy records that way you can simply add in yout database for testing.

test_viewer table
PHP Highcharts Column Chart Example
test_click table:
PHP Highcharts Column Chart Example
Step 2: Create Database Configuration File

Now this step, I need to create on mysql database configuration file. In this file we will add details of phpmyadmin username, password and database name, So let's create new file "db_config.php" and put bellow code.

<?php
    $dbHost = "localhost";
    $dbDatabase = "phpexample";
    $dbUser = "root";
    $dbPasswrod = "root";

    $mysqli = mysqli_connect($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
?>
Step 3: Create index.php File

Here this last step, we have to just create index.php file in root folder. In this file i write code of getting data from mysql database and convert into json data. So let's create new file "index.php" and put bellow code.

<?php
    require('db_config.php');

    /* Getting test_viewer table data */
    $sql = "SELECT SUM(numberofview) as count FROM test_viewer 
            GROUP BY YEAR(created_at) ORDER BY created_at";
    $viewer = mysqli_query($mysqli,$sql);
    $viewer = mysqli_fetch_all($viewer,MYSQLI_ASSOC);
    $viewer = json_encode(array_column($viewer, 'count'),JSON_NUMERIC_CHECK);

    /* Getting test_click table data */
    $sql = "SELECT SUM(numberofclick) as count FROM test_click 
            GROUP BY YEAR(created_at) ORDER BY created_at";
    $click = mysqli_query($mysqli,$sql);
    $click = mysqli_fetch_all($click,MYSQLI_ASSOC);
    $click = json_encode(array_column($click, 'count'),JSON_NUMERIC_CHECK);

?>
<!DOCTYPE html>
<html>
<head>
    <title>HighChart</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () { 
    var data_click = <?php echo $click; ?>;
    var data_viewer = <?php echo $viewer; ?>;
    $('#container').highcharts({
        chart: {
            type: 'column'
        },
        title: {
            text: 'Yearly Website Ratio'
        },
        xAxis: {
            categories: ['2013','2014','2015', '2016']
        },
        yAxis: {
            title: {
                text: 'Rate'
            }
        },
        series: [{
            name: 'Click',
            data: data_click
        }, {
            name: 'View',
            data: data_viewer
        }]
    });
});
</script>
<div class="container">
    <br/>
    <h2 class="text-center">Highcharts php mysql json example</h2>
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>
                <div class="panel-body">
                    <div id="container"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
now we are ready to run this example, so just run bellow command on root folder for run your project.
php -S localhost:8000
Now you can open bellow url on your browser:
http://localhost:8000

It will help you....

Laravel 8 Toastr Notifications using yoeunes/toastr package Tutorial

Laravel 8 Toastr Notifications using yoeunes/toastr package Tutorial

Laravel 8 Toastr Notifications using yoeunes/toastr package Example

Hi Guys

Today, I will learn with you how to install and use toastr notifications using yoeunes/toastr package in laravel application.we will use yoeunes/toastr package.we will write step be step tutorial for laravel toastr notifications.

Toastr notifications yoeunes/toastr package provides warning,success,error and info notifications.You have to just follow few step for implement toastr notifications in your laravel application. In this example i give you example from scratch. So just follow bellow step.

Step 1: Install yoeunes/toastr package

We need to install yoeunes/toastr composer package for datatable, so you can install using following command:

composer require yoeunes/toastr

After that you need to set providers and alias.

config/app.php
'providers' => [
    ...
    Yoeunes\Toastr\ToastrServiceProvider::class
    ...
];

As optional if you want to modify the default configuration, you can publish the configuration file:

php artisan vendor:publish --provider='Yoeunes\Toastr\ToastrServiceProvider' Step 2: Create Route

In this is step we need to create route for datatables layout file and another one for getting data. so open your routes/web.php file and add following route.

routes/web.php
<?php
use App\Http\Controllers\HomeController;
/*
|--------------------------------------------------------------------------
| 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('home',[HomeController::class,'index'])->name('home');
Step 5: Create Controller

In this step, now we should create new controller as HomeController. this controller will manage layout and getting data request and return response, so put bellow content in controller file:

app/Http/Controllers/HomeController.php Success Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->success('Success Message');
        return view('home');
    }
}
Error Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->error('Error Message');
        return view('home');
    }
}
Info Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->info('Info Message');
        return view('home');
    }
}
Warning Toastr Notifications For Controller Code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        toastr()->warning('Warning Message');
        return view('home');
    }
}
Step 3: Create View

In Last step, let's create users.blade.php(resources/views/home.blade.php) for layout and we will write design code here and put following code:

resources/views/home.blade.php
<!DOCTYPE html>
<html>
<head>
   <title>Laravel Toastr Notifications using yoeunes/toastr package</title>
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css">
   @toastr_css
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3 mt-5">
            <div class="card">
                <div class="card-header text-center ">
                    Laravel Toastr Notifications using yoeunes/toastr package  - nicesnippets.com
                </div>
                <div class="card-body text-center p-5">
                    Check For Toastr Notification
                </div>
            </div>
        </div>
    </div>
</div>
</body>
@jquery
@toastr_js
@toastr_render
</html>

Now, we are ready to check, so let's check...

It will help you...

Laravel Disable Register URL Example

Laravel Disable Register URL Example

Laravel Disable Register URL Example

Hi Guys

Today, I will learn to how to disable registration route in laravel. We can also register remove Authentication Routes from route file.i will disable register create custom route in laravel.

We will used register for default Auth::routes() in my web.php file. I Will used to auth remove register routes from route file.you can easy to disable register.

Here the following example of disable register

Example: 1

Now this example in register false for add in auth route in create in web.php('routes/web.php') file.

following path:/routes/web.php
Auth::routes(['register' => false]);
Example: 2

Here this example in register disable for add in custom route in create in web.php('routes/web.php') file.

following path:/routes/web.php
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');

// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');

It will help you...

Laravel Cron Job Task Scheduling Example

Laravel Cron Job Task Scheduling Example

Laravel Cron Job Task Scheduling Example

Hi Dev

In this blog, I will learn how to create Cron Job Task Scheduling in laravel we will give you simple example of cron job task scheduling with laravel. we will create example step by step of cron job using laravel task scheduling.

You can easy create a cron job task scheduling in laravel.Why we have to use cron job? and what is benefit to use cron jobs in laravel and how to setup cron job in laravel?, If you have this question then i will explain why.Many times we need to send notifications or send email automatically to users for update property or items. So at that time you can define some basic logic for each days, hours etc can run and send email notification.

Here blow the example of cron job task scheduling

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 New Command

Here this step, we need to create our custom command. custom command will execute with task scheduling scron job. so, let's run bellow command to create new custom command.

php artisan make:command DemoCron --command=demo:cron

After make some changes on Command file.

following path: .app/Console/Commands/DemoCron.php
<?php
   
namespace App\Console\Commands;
   
use Illuminate\Console\Command;
   
class DemoCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'demo:cron';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
    
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \Log::info("Cron is working fine!");
     
        /*
           Write your database logic we bellow:
           Item::create(['name'=>'hello new']);
        */
      
        $this->info('Demo:Cron Cummand Run successfully!');
    }
}
Step 3: Register as Task Scheduler

Now this step, we need to define our commands on Kernel.php file with time when you want to run your command like as bellow functions

->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->everyTenMinutes(); Run the task every ten minutes
->everyFifteenMinutes(); Run the task every fifteen minutes
->everyThirtyMinutes(); Run the task every thirty minutes
->hourly(); Run the task every hour
->hourlyAt(17); Run the task every hour at 17 mins past the hour
->daily(); Run the task every day at midnight
->dailyAt(’13:00′); Run the task every day at 13:00
->twiceDaily(1, 13); Run the task daily at 1:00 & 13:00
->weekly(); Run the task every week
->weeklyOn(1, ‘8:00’); Run the task every week on Tuesday at 8:00
->monthly(); Run the task every month
->monthlyOn(4, ’15:00′); Run the task every month on the 4th at 15:00
->quarterly(); Run the task every quarter
->yearly(); Run the task every year
->timezone(‘America/New_York’); Set the timezone
following path: /app/Console/Kernel.php
<?php
   
namespace App\Console;
    
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
    
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\DemoCron::class,
    ];
     
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('demo:cron')
                 ->everyMinute();
    }
     
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
     
        require base_path('routes/console.php');
    }
}
Step 4: Run Scheduler Command For Test

Here we are ready to run our cron, so you can manually check using following command of your cron. so let's run bellow command

php artisan schedule:run

Next run above command, you can check log file where we already print some text. so open you your log file it looks like as bellow:

following path: /storage/logs/laravel.php
[2021-05-18 03:46:42] local.INFO: Cron is working fine!  
[2021-05-18 03:46:52] local.INFO: Cron is working fine!  
[2021-05-18 03:46:55] local.INFO: Cron is working fine!

At last you can manage this command on scheduling task, you have to add a single entry to your server’s crontab file:

* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1
OR
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

It will help you...

Laravel Get Base URL in Controller Example

Laravel Get Base URL in Controller

Hi Dev,

Today, I will learn to you how to create laravel get base url in the controller, we will create get base url in the controller. We will show a step by step simple get base url in laravel.

You may use the url or fullurl methods to get base url in the controller. the url method will return the url without the query string, while the full url method includes the query string using get base url in the controller. you can get using url facade methods to get base url in the controller.

Here examples following different types to get base url in the controller.

Example: 1 Now In this example url() method to get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = url()->full();
    print_r($url);
}
Example: 2 Now in this example in request facade of url method using get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = \Request::url();
    print_r($url);
}
Example: 3 Here in this example in request facade of fullUrl method using get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = \Request::fullUrl();
    print_r($url);
}
Example: 4 Now In this example in url facade of current method using get url in controller
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $url  = \URL::current();
    print_r($url);
}
It will help you...

Youtube Videos Download Source code

Youtube Videos Download Source code

Hi Guys,

Today,I will expound you how to download youtube videos source code.,I will show example of download youtube videos from source code, you can videos youtube video.you can easyliy youtube video download source code .I will download youtube videos in any formate useing loader api.

Here, I will give you full example for simply Youtube Videos Download Script code in loader.to api as bellow.

Example
<!DOCTYPE html>
<html>
<head>
  <title>Youtube Videos Download Script code</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="col-md-6 offset-md-3 mt-5">
    <div class="card">
      <div class="card-header bg-info">
        <h5>Youtube Videos Download Any Online Videos</h5>
      </div>
      <div class="card-body">
        <div class="row">
          <div class="col-md-12">
            <div class="form-group">
              <label class="text-weight"><b>Online Videos Link:</b></label>
              <input type="txt" name="link" class="form-control link" required>
            </div>
          </div>
        </div>
        <form class="form-download">
          <div class="row">
            <div class="col-md-12">
              <div class="form-group">
                <label class="text-weight"><b>Select Video Fromate:</b></label>
                <select class="form-control formte" required>
                  <option selected disabled>Select Video Formate</option>
                  <option value="mp3">Mp3</option>
                  <option value="mp4a">144 Mp4</option>
                  <option value="360">360 Mp4</option>
                  <option value="480">480 Mp4</option>
                  <option value="720">720 Mp4</option>
                  <option value="1080">1080 Mp4</option>
                  <option value="4k">4k Mp4</option>
                  <option value="8k">8k Mp4</option>
                </select>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-12">
              <div class="form-group mt-4 download-video">
                <button class="btn btn-success btn-block click-btn-down" type="submit">Click Me</button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</body>
<script type="text/javascript">
  $(".click-btn-down").click(function(){
      var link = $(".link").val();
    var fromate = $(".formte").children("option:selected").val();
    var src =""+link+"="+fromate+"";
    downloadVideo(link,fromate);
  });
  function downloadVideo(link,fromate) {
      $('.download-video').html('<iframe style="width:100%;height:60px;border:0;overflow:hidden;" scrolling="no" src="https://loader.to/api/button/?url='+link+'&f='+fromate+'"></iframe>');
  }
</script>
</html>

It will help you..

Laravel 8 Resource Routing Example

Laravel 8 Resource Routing Example

Hi Dev,

Today,I will explicate you how to engender resource route in laravel 8. we will show laravel 8 resource routing example.laravel resource routing assigns the typical "crud" routes to a controller with a single line of code. for example, you may wish to engender a controller that handles all http requests for "posts" stored by your application. utilizing the composition:controller artisan command, you can expeditiously engender such a controller.

You have to engender resource route on laravel they provide insert, update, view, efface routes and second you have to engender resource controller that will provide method for insert, update, view and efface.

Here ,I will engender a controller at app/Http/Controllers/PostController.php. The controller will contain a method for each of the available resource operations.

So, in this example we will visually perceive how to engender resource route and how they work.

we have to understand why we choose resource route instead of different route. we always declare different different route for our crud application like as bellow:

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

Route::get('posts', '[PostController::class, 'index']');
Route::get('posts/create', '[PostController::class, 'create']');
Route::post('posts', '[PostController::class, 'store']');
Route::get('posts/{post}/edit', '[PostController::class, 'edit']');
Route::put('posts/{post}', '[PostController::class, 'update']');
Route::get('posts/{post}', '[PostController::class, 'show']');
Route::delete('posts/{post}', '[PostController::class, 'destroy']');

As you can see above route declare, we have to create six routes for our crud application module. But we can simply create those six routes by using bellow resource route:

Here, you may register a resourceful route to the controller:

Resource Route: routes/web.php
use App\Http\Controllers\PostController;
Route::resource('posts', PostController::class);
Now, you can run bellow command and check create route lists:
php artisan route:list --name=posts
Now we have output as like bellow created route:
+--------+-----------+-------------------+---------------+---------------------------------------------+--------------+
| Domain | Method    | URI               | Name          | Action                                      | Middleware   |
+--------+-----------+-------------------+---------------+---------------------------------------------+--------------+
|        | GET|HEAD  | api/user          |               | Closure                                     | api,auth:api |
|        | GET|HEAD  | posts             | posts.index   | App\Http\Controllers\PostController@index   | web          |
|        | POST      | posts             | posts.store   | App\Http\Controllers\PostController@store   | web          |
|        | GET|HEAD  | posts/create      | posts.create  | App\Http\Controllers\PostController@create  | web          |
|        | GET|HEAD  | posts/{post}      | posts.show    | App\Http\Controllers\PostController@show    | web          |
|        | PUT|PATCH | posts/{post}      | posts.update  | App\Http\Controllers\PostController@update  | web          |
|        | DELETE    | posts/{post}      | posts.destroy | App\Http\Controllers\PostController@destroy | web          |
|        | GET|HEAD  | posts/{post}/edit | posts.edit    | App\Http\Controllers\PostController@edit    | web          |
+--------+-----------+-------------------+---------------+---------------------------------------------+--------------+

I will make:controller Artisan command, we can quickly create such a controller:

Resource Controller Command:
php artisan make:controller PostController --resource

Here you can see your PostController with following resource method, So let's open and see.

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

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController 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  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

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

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

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

this way you can simply use resource route and controller, make quick crud module for your project.

It Will help you...

Laravel date_format Validation Example

Laravel date_format Validation Example
Hi Guys,

In this tutorial I will show laravel Date Format Validation example You can validate date_format validation rules. With date_format:format method you can set the preferred date format, and the filed value must match the given format.

The field under validation must match the given format. You should use either date_format when validating a field, not both. This validation rule supports all formats supported by PHP's Date class.

Example
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function store(Request $request)
{
    $request->validate([
        'start_date' => 'date_format:d/m/Y',
        'end_date' => 'date_format:d/m/Y'
    ]);
}
OR
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function store(Request $request)
{
  $request->validate([
      'start_date' => 'date_format:Y-m-d',
      'end_date' => 'date_format:Y-m-d'
  ]);
}

It will help you ...

Laravel Guzzle Request Example

Laravel Guzzle Request Example

Hi Guys

Today, I will explain how to use laravel guzzle http client request? we will show example of guzzle http client request in laravel. we will guide you how to use guzzle http client GET and POST request with php laravel.

I will use guzzlehttp/guzzle composer package for guzzle http request in laravel application.we will install the guzzlehttp/guzzle package in laravel.

A Guzzle is a PHP HTTP client that makes it easy to send HTTP requests with data, headers and trivial to integrate with web services. Guzzle is a simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc.

Here following the step and you can get simple example of guzzle.

Install Guzzle Package

In this step, we will install guzzlehttp/guzzle package and then we can easily use thir method So let's just run bellow command.

composer require guzzlehttp/guzzle
Example of Requests Using Guzzle:

Here this step, I will show you how to run all above listed request you can use following controller method:

GET Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzleGetRequest()
{
    $client = new \GuzzleHttp\Client();
    $request = $client->get('http://ourexample.com');
    $response = $request->getBody();
   
    dd($response);
}
Post Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzlePostRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://ourexample.com/api/blog";
   
    $myBody['name'] = "Demo";
    $request = $client->post($url,  ['body'=>$myBody]);
    $response = $request->send();
  
}
Put Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzlePutRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://ourexample.com/api/blog/1";
    $myBody['name'] = "Demo";
    $request = $client->put($url,  ['body'=>$myBody]);
    $response = $request->send();
   
    dd($response);
}
Delete Request:
/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function guzzleDeleteRequest()
{
    $client = new \GuzzleHttp\Client();
    $url = "http://ourexample.com/api/blog/1";
    $request = $client->delete($url);
    $response = $request->send();

    dd($response);
}

It will help you...

Laravel Get Headers From Request Example

laravel get headers from request

Hi Dev,

In this blog ,I Will learn you how to get header in laravel. I will show example of laravel get headers from request you can easliy laravel get all headers from request. I will explain laravel get all headers.

I can blow you can easily get headers from request in laravel this example.

Exmaple:1

Here In this exmaple laravel Get headers from request to a header method

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(Request $request)
{
    $headers = $request->header('connection');

    dd($headers);
}
Output :
"keep-alive"
Exmaple:2

Here In this exmaple laravel get headers from request using a request builder to a header method

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
    $headers = \Request::header();

   dd($headers);
}
Output :
array:13 [
  "host" => array:1 [
    0 => "localhost:8000"
  ]
  "connection" => array:1 [
    0 => "keep-alive"
  ]
  "cache-control" => array:1 [
    0 => "max-age=0"
  ]
  "upgrade-insecure-requests" => array:1 [
    0 => "1"
  ]
  "user-agent" => array:1 [
    0 => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
  ]
  "sec-fetch-user" => array:1 [
    0 => "?1"
  ]
  "accept" => array:1 []
  "sec-fetch-site" => array:1 [
    0 => "same-origin"
  ]
  "sec-fetch-mode" => array:1 [
    0 => "navigate"
  ]
  "referer" => array:1 []
  "accept-encoding" => array:1 [
    0 => "gzip, deflate, br"
  ]
  "accept-language" => array:1 [
    0 => "en-US,en;q=0.9,la;q=0.8,gu;q=0.7"
  ]
  "cookie" => array:1 [
    0 => "_ga=GA1.1.2099257977.1573906086; __gads=Test; _gid=GA1.1.879789242.1575463476; __atuvc=13%7C46%2C68%7C47%2C5%7C48%2C17%7C49; XSRF-TOKEN=eyJpdiI6IlRZVE1VUnh2WFNu "
  ]
]
Exmaple:3

Here In this exmaple laravel Get headers from request to a getallheaders method

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
   $headers = getallheaders();

   dd($headers);
}
Output :
array:13 [
  "Host" => "localhost:8000"
  "Connection" => "keep-alive"
  "Cache-Control" => "max-age=0"
  "Upgrade-Insecure-Requests" => "1"
  "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
  "Sec-Fetch-User" => "?1"
  "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"
  "Sec-Fetch-Site" => "same-origin"
  "Sec-Fetch-Mode" => "navigate"
  "Referer" => "http://localhost:8000/login"
  "Accept-Encoding" => "gzip, deflate, br"
  "Accept-Language" => "en-US,en;q=0.9,la;q=0.8,gu;q=0.7"
  "Cookie" => "_ga=GA1.1.2099257977.1573906086; __gads=Test; _gid=GA1.1.879789242.1575463476; __atuvc=13%7C46%2C68%7C47%2C5%7C48%2C17%7C49; XSRF-TOKEN=eyJpdiI6IlRZVE1VUnh2WFNu "
]
Exmaple:4

Here In this exmaple laravel Get headers from request to a apache_request_headers method

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index()
{
   $headers = apache_request_headers();

   dd($headers);
}
Output :
array:13 [
  "Host" => "localhost:8000"
  "Connection" => "keep-alive"
  "Cache-Control" => "max-age=0"
  "Upgrade-Insecure-Requests" => "1"
  "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
  "Sec-Fetch-User" => "?1"
  "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"
  "Sec-Fetch-Site" => "same-origin"
  "Sec-Fetch-Mode" => "navigate"
  "Referer" => "http://localhost:8000/login"
  "Accept-Encoding" => "gzip, deflate, br"
  "Accept-Language" => "en-US,en;q=0.9,la;q=0.8,gu;q=0.7"
  "Cookie" => "_ga=GA1.1.2099257977.1573906086; __gads=Test; _gid=GA1.1.879789242.1575463476; __atuvc=13%7C46%2C68%7C47%2C5%7C48%2C17%7C49; XSRF-TOKEN=eyJpdiI6IlRZVE1VUnh2WFNu "
]

it will help you....

JQuery UI Slider Colorpicker Example

JQuery UI Slider Colorpicker Example

Hi Dev,

Today, I will engender slider colorpicker utilizing jquery ui. We will show you slider colorpicker in jquery ui. you can easliy make slider colorpicker example in jquery ui.We will make slider colorpicker example utilizing jquery ui.

I will give you full example of Jquery UI slider colorpicker Example.

Example
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Slider Colorpicker Example</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link href="https://fonts.googleapis.com/css2?family=K2D:wght@200&family=Pathway+Gothic+One&display=swap" rel="stylesheet">
    <style>
        body{
            background-color: #000 !important;
            font-family: 'K2D', sans-serif;
        }
        .content{
            height:200px;
            padding:45px 40px;
            margin:150px auto;
            width:35%;
            background:#fff;
        }
        #red, #green, #blue {
            float: left;
            clear: left;
            width: 300px;
            margin: 15px;
        }
        #swatch {
            width: 120px;
            height: 100px;
            margin-top: 18px;
            margin-left: 350px;
            background-image: none;
        }
        #red .ui-slider-range { background: #ef2929; }
        #red .ui-slider-handle { border-color: #ef2929; }
        #green .ui-slider-range { background: #8ae234; }
        #green .ui-slider-handle { border-color: #8ae234; }
        #blue .ui-slider-range { background: #729fcf; }
        #blue .ui-slider-handle { border-color: #729fcf; }
    </style>
</head>
<body class="ui-widget-content" style="border:0;">
    <div class="content">
        <p class="ui-state-default ui-corner-all ui-helper-clearfix" style="padding:4px;">
            <span class="ui-icon ui-icon-pencil" style="float:left; margin:-2px 5px 0 0;"></span>Simple Colorpicker
        </p>
        <div id="red"></div>
        <div id="green"></div>
        <div id="blue"></div>
        <div id="swatch" class="ui-widget-content ui-corner-all"></div>
    </div>
</body>
<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>
<script>
    $(function(){
        function hexFromRGB(r, g, b) {
            var hex = [
                r.toString( 16 ),
                g.toString( 16 ),
                b.toString( 16 )
            ];
            $.each( hex, function( nr, val ) {
                if ( val.length === 1 ) {
                    hex[ nr ] = "0" + val;
                }
            });
            return hex.join( "" ).toUpperCase();
        }
        function refreshSwatch(){
            var red = $( "#red" ).slider( "value" ),
            green = $( "#green" ).slider( "value" ),
            blue = $( "#blue" ).slider( "value" ),
            hex = hexFromRGB( red, green, blue );
            $( "#swatch" ).css( "background-color", "#" + hex );
        }
        $("#red, #green, #blue").slider({
            orientation: "horizontal",
            range: "min",
            max: 255,
            value: 127,
            slide: refreshSwatch,
            change: refreshSwatch
        });
        $("#red").slider("value", 255);
        $("#green").slider("value", 140);
        $("#blue").slider("value", 60);
    });
</script>
</html>

It will help you...

JQuery UI Progressbar Download Dialog

JQuery UI Progressbar Download Dialog
Hi Dev, Today, I will engender progressbar with download dialog utilizing jquery ui. We will show you progressbar with download dialog in jquery ui.you can easliy make progressbar with download dialog example in jquery ui. I will give you full example of Jquery UI progressbar with download dialog Example. Example
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Progressbar - Download Dialog Example</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <style>
        #progressbar {
            margin-top: 20px;
        }
        .progress-label {
            font-weight: bold;
            text-shadow: 1px 1px 0 #fff;
        }
        .ui-dialog-titlebar-close {
            display: none;
        }
        .container{
            margin-top:200px;
            text-align: center;
        }
        #downloadButton{
            border-radius:0px;
            border:1px solid green;
            background:green;
            color:#fff;
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="dialog" title="File Download">
            <div class="progress-label">Starting download...</div>
            <div id="progressbar"></div>
        </div>
        <button id="downloadButton">Start Download</button>
    </div>
</body>
<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>
<script type="text/javascript">
    $(function(){
        var progressTimer,
        progressbar = $( "#progressbar" ),
        progressLabel = $( ".progress-label" ),
        dialogButtons = [{
            text: "Cancel Download",
            click: closeDownload
        }],
        dialog = $( "#dialog" ).dialog({
            autoOpen: false,
            closeOnEscape: false,
            resizable: false,
            buttons: dialogButtons,
            open: function() {
              progressTimer = setTimeout( progress, 2000 );
            },
            beforeClose: function() {
              downloadButton.button( "option", {
                disabled: false,
                label: "Start Download"
              });
            }
        }),
        downloadButton = $( "#downloadButton" )
            .button()
            .on( "click", function() {
              $( this ).button( "option", {
                disabled: true,
                label: "Downloading..."
              });
              dialog.dialog( "open" );
        });
        progressbar.progressbar({
            value: false,
            change: function() {
                progressLabel.text( "Current Progress: " + progressbar.progressbar( "value" ) + "%" );
            },
            complete: function() {
            progressLabel.text( "Complete!" );
            dialog.dialog( "option", "buttons", [{
            text: "Close",
            click: closeDownload
            }]);
            $(".ui-dialog button").last().trigger( "focus" );
        }
    });
 
    function progress() {
        var val = progressbar.progressbar( "value" ) || 0;
        progressbar.progressbar( "value", val + Math.floor( Math.random() * 3 ) );
            if(val <= 99) {
            progressTimer = setTimeout( progress, 50 );
        }
    }
 
    function closeDownload() {
        clearTimeout( progressTimer );
        dialog
        .dialog( "option", "buttons", dialogButtons )
        .dialog( "close" );
        progressbar.progressbar( "value", false );
        progressLabel
        .text( "Starting download..." );
        downloadButton.trigger( "focus" );
        }
    });
</script>
</html>
It will help you...

Laravel One to Many Polymorphic Eloquent Relationship

Laravel One to Many Polymorphic Eloquent Relationship

Today, I Will explicate you how to utilize One to Many polymorphic eloquent relationship in laravel application. We can engender migration with peregrine key schema, retrieve records, insert incipient records, records etc. I will show you laravel morphMany relationship example.

We will engender three table "projects", "videos" and "messages" and both table are connected with each other, I will utilize One to Many polymorphic relationship with each other by utilizing laravel Eloquent Model, We will first engender database migration, then model, retrieve records and then how to engender records too.One to Many polymorphic Relationship use "morphMany()" and "morphTo()" for cognation.

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

Step:1 Create Migration

In this step, we will need two tables in our database project, videos and messages.I will start to create the model and migrations, then we will define the one to morphMany relationship.To generate models and migrations, run below two commands in your terminal.

php artisan make:model Project -m

php artisan make:model Video -m

php artisan make:model Message -m

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

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

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

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

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

class CreateMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->id();
            $table->text('body');
            $table->integer('message_id');
            $table->string('message_type');
            $table->timestamps();
        });
    }

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

Now run the below command to create project, videos and messages tables in your database:

php artisan migrate
Step:2 Create Model Relationship

Now in this step, we have project, videos and messages tables ready, let’s define the one to manMany relationship in our models. our app\project.php model file and add a new function called message() which will return a morphMany relationship like below:

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

class Project extends Model
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = ['name'];
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function message()
    {
        return $this->morphMany(Message::class, 'message');
    }
}
app\Video.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = ['name'];
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function message()
    {
        return $this->morphMany(Message::class, 'message');
    }
}

you can see, in the message() method we are defining a morphMany relationship on message model.

Now we will defining Inverse One to Many polymorphic Relationship in Laravel.As we have defined the morphMany relationship on Brand model which return the cognate records of message model, we can define the inverse relationship on the message model.Open your app\message.php model file and integrate an incipient method called message() in it which will return the cognate brand of a message.

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

class Message extends Model
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = ['body','message_id','message_type'];
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function message()
    {
        return $this->morphTo();
    }
}

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

Step 3 : Insert Records

Let’s in this step add data to project, videos and messages from controller:

app\Http\Controllers\ProjectController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Project;
use App\Video;
use App\Message;

class ProjectController extends Controller
{
    public function project()
    {   
       //project message add
       $project = Project::find(1);   
 
       $message = new Message;
       $message->body = "Hi itwebtuts.com";
     
       $project->messages()->save($message);

       //video message add
       $video = Video::find(1);   
 
       $message = new Message;
       $message->body = "Hi itwebtuts.com";
     
       $video->messages()->save($message);
    }
}
Step 4 : Retrieve Records

Now in this step retrieve records model

app\Http\Controllers\ProjectController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Project;
use App\Video;
use App\Message;

class ProjectController extends Controller
{
    public function project()
    {   
       //project message retrieve 
       $project = Project::find(1);   
       dd($project->messsage);

       //video message Retrieve
       $video = Video::find(1);   
       dd($video->message);
     }
}

it will help you....

Laravel 8 Custom Error Page Tutorial

how to create custom error page in laravel?

Hi Dev,

Today,I will learn you how engender Custom Error Page in laravel 8. we will show example of laravel 8 custom error page example . you will learn how to engender custom error page in laravel 8. you will learn how to engender 404 error page in laravel 8. we will avail you to give example of how to set 404 error page in laravel 8. if you optate to optically discern example of laravel 8 custom 404 page then you are a right place. Let's get commenced with laravel 8 incipient error page example.

You require to engender blade file like 404.blade.php, 405.blade.php etc on errors(resources/view.errors) directory in laravel 8. you can optically discern i engendered 404 blade file and check it on your project.

Virtually we are utilizing theme for front-end or backend side and we always probing for set 404, 500 or 505 error page design from there that we utilized for project. So it is a very simple and facile way to engender custom 404 page in laravel 8 project. i integrated below screen shot of laravel 8 error page design.

Now you have to just engender "errors" folder in your resources directory and then after you require to engender 404.blade.file inside that folder. So, fundamentally laravel 8 will stetted default design, but if you engendered 404 file into "errors" directory then it will take from there

So, you just need to engender 404 blade file and put your own code like i integrated then you can simply check it out.

resources/views/errors/404.blade.php
<!DOCTYPE html>
<html>
<head>
   <title>Custom Error Page</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" ></script>
    <style type="text/css">
       .error-div{
          margin-top: 200px;
          background: #c1c1c1;
          padding: 70px;
          border-radius: 5px;
       }
       .error-div h1{
          font-size: 50px;
         font-weight: bold;          
       }
       .error-div h6{
          font-family: ubuntu;
          font-size: 20px;
       }
    </style>
</head>
<body>
   <div class="container">
      <div class="row text-center">
        <div class="col-md-6 offset-md-3 error-div">
          <h1>404</h1>
          <h6>Page not found - Itwebtuts.com</h6>
        </div>
      </div>
    </div>
</body>
</html>

After you can simply run your application by following command:

php artisan serve

Now you can open following url and you will see error page as above:

http://localhost:8000/okgays

Now you can simply check it out.

Output

I will help you...

Bootstrap Datepicker - Disabled Specific dates and Saturday,Sunday

Bootstrap Datepicker - Disabled Specific dates and Saturday,Sunday

Hi Dev,

Today, i will give you simple example of Boostrap datepicker datesDisabled array of dates and Sunday & Saturday. so bacially, you can enable and disable specific dates array with also enable disable saturday and sunday in bootstrap datepicker.

it will useing beforeShowDay options to disable Specific days in bootstrap datepicker. we are disabled Bootstrap Datepicker in Sunday & Saturday and particular Sunday & Saturday enable useing beforeShowDay.

Example
<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Datepicker - Disabled Specific dates and Saturday,Sunday</title>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css">
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js"></script>
</head>
<body>
<div class="container">
   <div class="row">
      <div class="col-md-7 offset-md-3 mt-5">
         <div class="card">
            <div class="card-header bg-light">
               <h6>Bootstrap Datepicker - Disabled Specific dates and Saturday,Sunday</h6>
            </div>
            <div class="card-body">
               <form action="#">
                  <div class="row">
                     <div class="col-md-12">
                        <div class="form-group">
                           <label>Date:</label>
                           <input type="text"  name="date" class="datepicker form-control" autocomplete="off">
                        </div>
                     </div>
                  </div>
                  <div class="row">
                     <div class="col-md-12">
                        <input type="submit" class="btn btn-success btn-block">
                     </div>
                  </div>
               </form>
            </div>
         </div>
      </div>
   </div>
</div>
<script type="text/javascript">
$(function() {
   var enableDays = ['2019-11-30'];
   var disabledDays = ['2019-11-28', '2019-11-29'];

   function formatDate(d) {
     var day = String(d.getDate())
     //add leading zero if day is is single digit

     if (day.length == 1)
       day = '0' + day
     var month = String((d.getMonth()+1))
     //add leading zero if month is is single digit
     if (month.length == 1)
       month = '0' + month
     return d.getFullYear() + '-' + month + "-" + day;
   }

   $('.datepicker').datepicker({
        format: 'mm/dd/yyyy',
         beforeShowDay: function(date){
          var dayNr = date.getDay();
            if (dayNr==0  ||  dayNr==6){
                if (enableDays.indexOf(formatDate(date)) >= 0) {
                    return true;
                }
                return false;
            }
            if (disabledDays.indexOf(formatDate(date)) >= 0) {
               return false;
            }
            return true;
        }
   });
});
</script>
</body>
</html>

it will help you.....

Laravel 8 Auth using Jetstream Example

Laravel 8 Auth using Jetstream Example

Hi Dev,

Today, I will show you laravel 8 authentication using jetstream. In this blog, I will give you simple example of laravel 8 auth with jetstream. you can see jetstream with auth in laravel 8 application. i would like to share with you laravel 8 jetstream auth with inertia.

Few days ago laravel 8 realeased and they provides lot's of new updates. laravel 7 was using laravel/ui for auth scaffolding and now laravel 8 provide jetstream for login, registration, email verification, two-factor authentication, session management, API support and team management.

Laravel 8 designed by Tailwind CSS and they provide auth using livewire and Inertia. i will show you how to add auth in laravel 8. you can easily create laravel auth with jetstream step by step.

Here I will give full example for jetstream with auth in laravel 8, So let's follow bellow step by step.

Laravel 8 Auth Scaffolding using Livewire Jetstream

Laravel Livewire is a library that makes it simple to build modern, reactive, dynamic interfaces using Laravel Blade, Laravel controller and Laravel validation.

Livewire provide way to write your ajax with laravel blade, validation and all, you can use as javascript framework. so let's see bellow step to create auth using laravel 8 livewire.

Install Laravel 8:

Here you can install laravel 8 application using bellow command to get laravel 8:

composer create-project --prefer-dist laravel/laravel blog
Install Jetstream:

Now, you can install jetstream using bellow command so lets open terminal and run bellow command:

composer require laravel/jetstream
Create Auth with Livewire:

Now we need to create authentication using bellow command you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:

php artisan jetstream:install livewire
  
OR
  
php artisan jetstream:install livewire --teams

Now, let's node js package:

npm install

let's run package:

npm run dev

Now, we have to need migration so let's bellow artisan command to migrate database:

php artisan migrate

Now, you can run and check. they installed all views, actions and all in your laravel 8 application.

Laravel 8 Auth Scaffolding using Inertia Jetstream

Laravel Inertia is a templating language and Inertia is working with vue js.

Install Laravel 8:

Here you can install laravel 8 application using bellow command to get laravel 8:

composer create-project --prefer-dist laravel/laravel blog
Install Jetstream:

Now, you can install jetstream using bellow command so lets open terminal and run bellow command:

composer require laravel/jetstream
Create Auth with Inertia:

Now we need to create authentication using bellow command you can create basic login, register and email verification. if you want to create team management then you have to pass addition parameter. you can see bellow commands:

php artisan jetstream:install inertia
  
OR
  
php artisan jetstream:install inertia --teams

Now, let's node js package:

npm install

let's run package:

npm run dev

Now, we have to need migration so let's bellow artisan command to migrate database:

php artisan migrate

Now, you can run and check. they installed all views, actions and all in your laravel 8 application.

Laravel 8 Jetstream Features

Laravel 8 jetstream provides lot's of features. you can see all features in configuration file fortify.php and jetstream.php file where you can enable and disable option for that feature:

config/fortify.php
....
  
'features' => [
        Features::registration(),
        Features::resetPasswords(),
        Features::emailVerification(),
        Features::updateProfileInformation(),
        Features::updatePasswords(),
        Features::twoFactorAuthentication(),
    ],
...
config/jetstream.php
....
  
'features' => [
        Features::profilePhotos(),
        Features::api(),
        Features::teams(),
    ],
...

Now you can run your application by bellow command:

php artisan serve

It will help you...

How To Create Event Example In Laravel 8?

How To Create Event Example In Laravel 8?

Hi Dev,

Today,I will learn you how to create event example in laravel 8.We will show simple event example in laravel 8.Events provides a simple observer implementation, allowing you to subscribe and listen for events in your application. In this posts you can learn how to create event for email send in your laravel 8 application. event is very help to create proper progmamming way. First create event using bellow command.

Step 1: Create Event
php artisan make:event SendMail
Next ,you can see file in this path

app/Events/SendMail.php and put bellow code in that file.

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class SendMail
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $userId;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($userId)
    {
        $this->userId = $userId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
Step 2: Listener

Now, I need to create event listener for "SendMail" event. So create event listener using bellow command.

php artisan make:listener SendMailFired --event="SendMail"

In this event listener we have to handle event code, i mean code of mail sending, Before this file you have to check your mail configration, If you did not set then you can set this way :How to set gmail configration for mail in Laravel 8?. Then you have to put bellow code on app/Listeners/SendMailFired.php.

<?php

namespace App\Listeners;

use App\Events\SendMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\User;
use Mail;

class SendMailFired
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  SendMail  $event
     * @return void
     */
    public function handle(SendMail $event)
    {
        $user = User::find($event->userId)->toArray();

        Mail::send('eventMail', $user, function($message) use ($user) {
            $message->to($user['email']);
            $message->subject('Event Testing');
        });
    }
}
Step 3: Providers

Now we require to register event on EventServiceProvider.php file so, open app/Providers/EventServiceProvider.php and copy this code and put in your file.

<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Events\SendMail;
use App\Listeners\SendMailFired;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        SendMail::class => [
            SendMailFired::class,
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}
Step 4:Create Route

Now In This Setp, we are create route.

use App\Http\Controllers\EventController;
Route::get('/event', [EventController::class, 'index'])->name('event.index');
Step 5: Create Controller

At Last we are ready to use event in our controller file. so use this way:

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

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Event;
use App\Events\SendMail;

class EventController extends Controller
{
    public function index()
    {
    	Event::dispatch(new SendMail(1));
    	dd('hi');
    }
}

Now we are ready to run our event example with laravel 8 so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/event

It will help you...