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

Jquery Textarea Auto Height Based on Content Example

Jquery Textarea Auto Height Based on Content Example

Hi Dev,

In this blog,I will learn you how to create textarea auto height based on content useing Jquery.we will show example of jquery textarea auto height based on content. if you want to see example of resize textarea to fit content then you are a right place. you can see auto resize textarea jquery. step by step explain auto expand textarea jquery. follow bellow step for auto adjust textarea height jquery.

You need to set textarea auto height based on content using jquery then i will help you how to auto resize height of textarea in jquery. i will give you two examples of auto adjust textarea height using jquery.

Example: 1
<!DOCTYPE html>
<html>
<head>
    <title>Javascript Auto-resize Textarea as User Types Example - nicesnippets.com</title>
</head>
<body>
<h1>Javascript Auto-resize Textarea as User Types Example</h1>
<strong>Body:</strong>
<br/>
<textarea id="body" style="width: 400px;"></textarea>
<script type="text/javascript">
    textarea = document.querySelector("#body"); 
    textarea.addEventListener('input', autoResize, false); 
  
    function autoResize() { 
        this.style.height = 'auto'; 
        this.style.height = this.scrollHeight + 'px'; 
    }
</script>
</body>
</html>
Example:2
<!DOCTYPE html>
<html>
<head>
    <title>Textarea Auto Height Based on Content Jquery</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<h1>Textarea Auto Height Based on Content Jquery Example - nicesnippets.com</h1>
<strong>Body:</strong>
<br/>
<textarea id="body" style="width: 400px;"></textarea>
<script type="text/javascript">
    $('#body').on('input', function () { 
        this.style.height = 'auto'; 
  
        this.style.height = (this.scrollHeight) + 'px'; 
    }); 
</script>
</body>
</html>

It will help you...

Laravel 8 Image With Grayscale Example

Hi Guys,

Today,I will learn you how to use image with grayscale in laravel 8. We will show example of image with grayscale in laravel 8. Spatie package is Image manipulation doesn't have to be hard. This PHP package makes it super easy to apply common manipulations to images like resizing, cropping and adding effects.

Here, I will give you full example for simply image with grayscale using Laravel 8 as bellow.

Step 1 : Install Laravel 8 Application

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

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

In this step, i will install spatie package for bellow command.

composer require spatie/image
Step 3: Create Routes

In next step, we will add new two routes in web.php file. One route for generate image upload form and another for post method So let's simply create both route as bellow listed:

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

here this step now we should create new controller as ImageWithgrayscaleController,So run bellow command for generate new controller

php artisan make:controller ImageWithgrayscaleController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Image;

class ImageWithgrayscaleController extends Controller
{
    public function index()
    {
      return view('imageWithgrayscale');
    }

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

      $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $image = $input['image'];
        
        $input['image'] = time().'.'.$image->getClientOriginalExtension();

        $img = Image::make($image->getRealPath());

        $img->grayscale()->save(public_path('/images').'/'.$input['image']);

        return redirect()->back()->with('success','Image Uploaded Successfully')->with('image',$input['image']);
    }
}
Step 5: Create Blade File

At last step we need to create imageWithgrayscale.blade.php file. So copy bellow and put on that file.

<!DOCTYPE html>
<html>
<head>
  <title>Grayscale Image Uploading Demo</title>
</head>
<body>
<div class="container">
  <div class="row mt-5">
    <div class="col-md-6 offset-md-3 mb-3">
      <h2>Grayscale Image Uploading Demo </h2>

      @if (count($errors) > 0)
        <div class="alert alert-danger">
          <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
          </ul>
        </div>
      @endif

      @if ($message = Session::get('success'))
        <div class="alert alert-success alert-block">
          <button type="button" class="close" data-dismiss="alert">×</button>  
            <strong>{{ $message }}</strong>
        </div>
        <div class="row">
          <div class="col-md-12">
            <strong>Grayscale Image:</strong><br/>
            <img src="/images/{{ Session::get('image') }}" width="500px" />
          </div>
        </div>
      @endif
      {!! Form::open(array('route' => 'image.grayscale.store','enctype' => 'multipart/form-data')) !!}
        <div class="row">
          <div class="col-md-12">
            <div class="form-group">
              <strong>Image:</strong>
              {!! Form::file('image', array('class' => 'form-control image')) !!}
            </div>
          </div>
          <div class="col-md-12 text-center">
            <button type="submit" class="btn btn-success">Upload Image</button>
          </div>
        </div>
      {!! Form::close() !!}
    </div>
  </div> 
</div>
</body>
</html>

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

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/image-grayscale

It will help you....

Laravel 8 Send Mail using Mailgun Tutorial

Laravel 8 Send Mail using Mailgun Tutorial

Hi Dev,

In this blog,I will learn you how to send mail using mailgun in laravel 8.we will show setp by step send mail using mailgun example in laravel 8.Mailgun is very popular API to send email from website. It is very fast to send mail and also it track the mail. Tracking email is very important feature of mailgun api and you can also see how much user open your mail, click on your mail too. Mailgun send mail like work gun.

I would like to show you how to setting of mailgun in our laravel 8 application. In this example you can learn to send simple mail using mailgun api. If you are use mailgun for sending email then you can save loading time and you can get mail fast.

Step 1: .env

First we will add configration on mail. i added my gmail account configration. so first open .env file and bellow code:

MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=yourUserName
MAIL_PASSWORD=yourPassword
MAIL_ENCRYPTION=tls
Step 2: Get Domain and Secret

Now, I need to add secret and domain of mailgun api configration. So first create new account in mailgun.com SignUp if you don't have before. After registeration active your mailgun account and click on Domails and click on Add New Domail button. then you can see bellow screen.

Laravel 8 Send Mail using Mailgun Tutorial

Next add name you can see bellow screen and copy domain name and API Key from like bellow image.

Laravel 8 Send Mail using Mailgun Tutorial
Step 3: Services

Now you have to open services.php and add mailgun configration this way :

config/services.php
'mailgun' => array(
'domain' => 'your_domain',
'secret' => 'your_secret',
),
Step 4: Routes

Here we are ready to send mail for test so first create test route for email sending.

app/Http/routes.php
use App\Http\Controllers\MailGunController;
Route::get('/send-mail-using-mailgun', [MailGunController::class, 'index'])->name('send.mail.using.mailgun.index');
Step 5: Controllers

Next,We are add mail function in MailGunController.php file so add this way :

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

namespace App\Http\Controllers;

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

class MailGunController extends Controller
{
    public function index()
    {
    	$user = User::find(1)->toArray();

	    Mail::send('mailView', $user, function($message) use ($user) {
	        $message->to($user['email']);
	        $message->subject('Testing Mailgun');
	    });

	    dd('Mail Send Successfully');
    }
}

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

Step 6: Blade resources/views/emails/mailEvent.blade.php
Hi, I am from itwebtuts.blogspot.com from mailgun testing.

Now we are ready to run our send mail using mailgun 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/send-mail-using-mailgun

It will help you...

Flutter Radio Button Tutorial Example

Flutter Radio Button Tutorial Example
Hi Dev,

Today, I will learn you how to create radio button in flutter. You can easily create radio button in flutter.First i will import package:flutter/material.dart, after I will make radio button using Container in Radioin flutter.

Here, I will give you full example for simply display radio button using flutter as bellow.

Example- Complete flutter radio button source code for main.dart file

In this step, You will open main.dart and Create a Container widget then put the radio button widget inside it.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Itwebtuts',
      theme: ThemeData(
        primarySwatch: Colors.red,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Welcome to Itwebtuts'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  State createState() => State();
}



class _State extends State {
  TextEditingController nameController = TextEditingController();
  int _radioValue = 0;

  void _handleRadioValueChange(int value) {
    setState(() {
      _radioValue = value;

      switch (_radioValue) {
        case 0:
          break;
        case 1:
          break;
        case 2:
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Itwebtuts'),
        ),
        body: Padding(

            padding: EdgeInsets.all(10),

            child: ListView(
              children: [
                Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.all(10),
                    margin: const EdgeInsets.only(top: 50),
                    child: Text(
                      'Radio Button',
                      style: TextStyle(
                          color: Colors.red,
                          fontWeight: FontWeight.w500,
                          fontSize: 30),
                    )),
                new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    new Radio(
                      value: 0,
                      groupValue: _radioValue,
                      onChanged: _handleRadioValueChange,
                    ),
                    new Text(
                      'First',
                      style: new TextStyle(fontSize: 16.0),
                    ),
                    new Radio(
                      value: 1,
                      groupValue: _radioValue,
                      onChanged: _handleRadioValueChange,
                    ),
                    new Text(
                      'Second',
                      style: new TextStyle(
                        fontSize: 16.0,
                      ),
                    ),
                    new Radio(
                      value: 2,
                      groupValue: _radioValue,
                      onChanged: _handleRadioValueChange,
                    ),
                    new Text(
                      'Last',
                      style: new TextStyle(fontSize: 16.0),
                    ),
                  ],
                ),
                Container(
                    height: 50,
                    padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: RaisedButton(
                      textColor: Colors.white,
                      color: Colors.red,
                      child: Text('Button'),
                      onPressed: () {
                        print(nameController.text);
                      },
                    )),
              ],
            )));
  }


}

It will help you..

Laravel 8 Custom Validation Rules Tutorial

Laravel 8 Custom Validation Rules Tutorial

Hi Dev,

Today,I will learn you how to use custom validation rules in laravel 8. We will show laravel 8 custom validation rules example you can easliy create custom validation rules in laravel 8.Validation is a primary requirement of every project, without validation we can not release successful application or website. Because if you haven't implemented validation then you get wrong information from use input. Laravel provide there are several default validation rules like required, max, min, array, unique, digits, in, boolean, before, after etc. We can simple use those validation rules in laravel 8 application. But if you require to create your own custom validation like given value should be in uppercase or lowercase etc as we require.

Now, we will simple represent how to make custom validator rules in laravel 8 application and it is very simple, so you have to just follow bellow step, make sure you can create only for laravel 8

we make example from scratch. In this example i take number text field and you can just enter even number, If you enter odd number then you got validation error.

Step 1: Create Custom Validation Rule

In first step, we will create custom validation rules by run following command. Bellow command through you can create Validation rules file and we can write a logic on that file. So let's run bellow command.

php artisan make:rule CheckPriceRule

Now, after successfully run above command, you will found new "rules" folder in app directory. In rules folder you will also found CheckPriceRule.php file. We have to simple write logic there, if you enter even number then return true otherwise don't do anything.

So, you should have file like as bellow:

app/Rules/CheckPriceRule.php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CheckPriceRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($value < 300) {
            return true;
        }
    }

    /**
     * Get the validation error messPrice.
     *
     * @return string
     */
    public function messPrice()
    {
        return 'The :attribute must be less than 300.';
    }
}
Step 2: Add Routes

Here, we need to add two routes for create form get method and another for post method. so open your routes/web.php file and add following route.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageResizeController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use App\Http\Controllers\CustomValidationController;

//Custom Validation
Route::get('/custom-validation', [CustomValidationController::class, 'index'])->name('custom.validation.index');
Route::post('/custom-validation/store', [CustomValidationController::class, 'store'])->name('custom.validation.store');
Step 3: Create CustomValidationController

Here, now we should create new controller as CustomValidationController. So run bellow command and create new controller. bellow controller for create controller.

php artisan make:controller CustomValidationController

Next bellow command you will find new file in this path app/Http/Controllers/CustomValidationController.php.

In this controller will create seven methods by default as bellow methods:

  • 1)index()
  • 2)store()

So, let's copy bellow code and put on CustomValidationController.php file.

app/Http/Controllers/CustomValidationController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Rules\CheckPriceRule;

class CustomValidationController extends Controller
{
    public function index()
    {
    	return view('customValidation');
    }

    public function store(Request $request)
    {
    	$request->validate([
            'name' => 'required',
            'price' => [
                'required', 
                new CheckPriceRule()
            ]
        ]);

    	dd("continue...");
    }
}
Step 4: Create View File

In this last step, we have to create customValidation.blade.php file, in this file we will create form and display validation error so let's create customValidation.blade.php file and put bellow code:

resources/views/customValidation.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Custom Validation</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha256-NuCn4IvuZXdBaFKJOAcsU2Q3ZpwbdFisd5dux4jkQ5w=" crossorigin="anonymous" />
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-3 mt-5">
            <div class="card mt-5">
                <div class="card-header text-center bg-info">
                    <h2 class="text-white"> <strong>Custom Validation</strong></h2>
                </div>
                <div class="card-body">
                    @if (count($errors) > 0)
                        <ul class="alert alert-danger pl-5">
	                        @foreach($errors->all() as $error)
	                           <li>{{ $error }}</li> 
	                        @endforeach
                        </ul>
                    @endif
                    <form action="{{ route('custom.validation.store') }}" method="post">
                        @csrf
                        <div class="form-group">
                            <label>Name</label>
                            <input type="text" name="name" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>Price</label>
                            <input type="text" name="price" class="form-control">
                        </div>
                        <div class="text-center">
                            <button class="btn btn-success"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
Now we are ready to run our custom validation rules example so run bellow command for quick run:
php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/custom-validation

It will help you...

Jquery Email Autocomplete Example

Jquery Email Autocomplete Example
Hi Dev,

Today,I Will learn you how to implement email autocomplete in jquery.you can easliy create email autocomplete in jquery.email-autocomplete plugin through we can simple email autocomplete in our laravel,PHP, .net or etc project.

In this example i use bellow js and css

-jquery.js

-jquery.email-autocomplete.min.js

-bootstrap.min.css

Example
<!DOCTYPE html>
<html>
<head>
    <title>Jquery email autocomplete example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/email-autocomplete/0.1.3/jquery.email-autocomplete.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style type="text/css">
        .eac-sugg {
          color: #ccc;
        }
        .m-1{
            margin: 10px;
        }
    </style>
</head>
<body class="bg-success">
    <div class="col-lg-10  m-1">
        <h1>Jquery Email Autocomplete Example-Nicesnippets.com</h1>
        <label>Email:</label>
        <input id="email" name="email" class="form-control" type="email" placeholder="Enter Email" / autocomplete="off">
    </div>
    <script type="text/javascript">
        $("#email").emailautocomplete({
          domains: [
            "nicesnippets.com",
            "gmail.com",
            "yahoo.com",
            "hotmail.com",
            "live.com",
            "facebook.com",
            "outlook.com",
            "gmx.com",
            "me.com",
            "laravel.com",
            "aol.com"]
        });
    </script>
</body>
</html>

It will help you...

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