Friday, February 28, 2020

Laravel 6 Event Broadcasting Socket.io Tutorials


Laravel 6 Event Broadcasting Socket.io Tutorials

Hello Buddies

In this tutorial I will guide you step by step through the use of event transfer with redis, socket.io and laravel-echo-server in the laravel 6 application. I will give you an example of a real-time broadcast message with io-socket in laravel 6. In laravel 6, Predis, Queue, Socket.io, Laravel-Echo-Server and event transmission are used.

You can easily do this. Just follow a few steps to create event sending using real-time broadcasting in Laravel 6.

Laravel has an event transfer problem. The transmission of events is very interesting and particularly difficult to implement with redis and socket.io. However, I will give you step-by-step instructions for sending real-time messages with quiet and socket io in the Laravel 6 application.

You only need to take a few steps to do the following. So follow the next steps and make real-time notification with Laravel.

Step 1: install Laravel 6


First, we need to get a new version of Laravel 6 with the following command because we are working from scratch. So open your terminal OR prompt and run the following command:

composer create-project --prefer-dist laravel/laravel blog


Step 2: install Predis


In this step we have to install predis as follows. So run the following command to install predis in the Laravel application.

composer require predis/predis


Step 3: create event


Here we have to create an event for the broadcast. In the event file, we need to set up the channel and send the message array with the key. Then run the following command to create an event.

php artisan make:event SendMessage

app/Events/SendMessage.php
<?php

  

namespace App\Events;

  

use Illuminate\Broadcasting\Channel;

use Illuminate\Queue\SerializesModels;

use Illuminate\Broadcasting\PrivateChannel;

use Illuminate\Broadcasting\PresenceChannel;

use Illuminate\Foundation\Events\Dispatchable;

use Illuminate\Broadcasting\InteractsWithSockets;

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

  

class SendMessage implements ShouldBroadcastNow

{

    use InteractsWithSockets, SerializesModels;

  

    public $data = ['asas'];

  

    /**

     * Create a new event instance.

     *

     * @return void

     */

    public function __construct()

    {

  

    }

  

    /**

     * Get the channels the event should broadcast on.

     *

     * @return \Illuminate\Broadcasting\Channel|array

     */

    public function broadcastOn()

    {

        return new Channel('user-channel');

    }

  

    /**

     * The event's broadcast name.

     *

     * @return string

     */

    public function broadcastAs()

    {

        return 'UserEvent';

    }

    /**

     * The event's broadcast name.

     *

     * @return string

     */

    public function broadcastWith()

    {

        return ['title'=>'This notification from ItSolutionStuff.com'];

    }

}


Step 4: Update the configuration file


In this step we need to add the configuration set in the env file and the database configuration file. You must configure the env file with BROADCAST_DRIVER as a redis and database configuration as well as a database redis configuration.

We will update the files:

.env
BROADCAST_DRIVER=redis

  

DB_DATABASE=blog_chat

DB_USERNAME=root

DB_PASSWORD=root

  

REDIS_HOST=localhost

REDIS_PASSWORD=null

REDIS_PORT=6379

   

LARAVEL_ECHO_PORT=6001


config/database.php
....

  

'redis' => [

  

    'client' => env('REDIS_CLIENT', 'predis'),

  

    'options' => [

        'cluster' => env('REDIS_CLUSTER', 'redis'),

        'prefix' => env('REDIS_PREFIX', ''),

    ],

  

    'default' => [

        'url' => env('REDIS_URL'),

        'host' => env('REDIS_HOST', '127.0.0.1'),

        'password' => env('REDIS_PASSWORD', null),

        'port' => env('REDIS_PORT', 6379),

        'database' => env('REDIS_DB', 0),

    ],

  

    'cache' => [

        'url' => env('REDIS_URL'),

        'host' => env('REDIS_HOST', '127.0.0.1'),

        'password' => env('REDIS_PASSWORD', null),

        'port' => env('REDIS_PORT', 6379),

        'database' => env('REDIS_CACHE_DB', 1),

    ],

  

],

....


Now we have to do the migration too.

So let's do the migration.

php artisan migrate


Step 5: Install the Laravel Echo Server


In this step we need to install the Laravel Echo Server on your system and in your project. So run the following command to install laravel-echo-server and init.

Install laravel-echo-server

npm install -g laravel-echo-server

Init laravel-echo-server

laravel-echo-server init

A new laravel-echo-server.json file is created as follows:

laravel-echo-server.json
{

 "authHost": "http://localhost",

 "authEndpoint": "/broadcasting/auth",

 "clients": [],

 "database": "redis",

 "databaseConfig": {

  "redis": {},

  "sqlite": {

   "databasePath": "/database/laravel-echo-server.sqlite"

  }

 },

 "devMode": true,

 "host": null,

 "port": "6001",

 "protocol": "http",

 "socketio": {},

 "secureOptions": 67108864,

 "sslCertPath": "",

 "sslKeyPath": "",

 "sslCertChainPath": "",

 "sslPassphrase": "",

 "subscribers": {

  "http": true,

  "redis": true

 },

 "apiOriginAllow": {

  "allowCors": false,

  "allowOrigin": "",

  "allowMethods": "",

  "allowHeaders": ""

 }

}


Step 6: Install npm, laravel-echo, socket.io-client


Here we install npm and also laravel-echo, socket.io-client. You also need a configuration. Then run the following command:

npm install

npm install laravel-echo

npm install socket.io-client

Now we have to create a new laravel-echo-setup.js file in the asset file.

resources/assets/js/laravel-echo-setup.js
import Echo from 'laravel-echo';

   

window.Echo = new Echo({

    broadcaster: 'socket.io',

    host: window.location.hostname + ":" + window.laravel_echo_port

});


You should now add the mix file as follows:

webpack.mix.js
...

mix.js('resources/assets/js/laravel-echo-setup.js', 'public/js');

Now we need to run the npm run command:

npm run dev


Step 7: update the view file


Now we have to update our Welcome Blade file. Here's how you can see our code:

resources/views/welcome.blade.php
<!doctype html>

<html lang="{{ app()->getLocale() }}">

    <head>

        <meta charset="utf-8">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>Laravel Broadcast Redis Socket io Tutorial - ItSolutionStuff.com</title>

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

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

        <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    </head>

    <body>

        <div class="container">

            <h1>Laravel Broadcast Redis Socket io Tutorial - ItSolutionStuff.com</h1>

            

            <div id="notification"></div>

        </div>

    </body>

  

    <script>

            window.laravel_echo_port='{{env("LARAVEL_ECHO_PORT")}}';

    </script>

    <script src="//{{ Request::getHost() }}:{{env('LARAVEL_ECHO_PORT')}}/socket.io/socket.io.js"></script>

    <script src="{{ url('/js/laravel-echo-setup.js') }}" type="text/javascript"></script>

      

    <script type="text/javascript">

        var i = 0;

        window.Echo.channel('user-channel')

         .listen('.UserEvent', (data) => {

            i++;

            $("#notification").append('<div class="alert alert-success">'+i+'.'+data.title+'</div>');

        });

    </script>

</html>


Step 8: call event


Here we create a new test route for the calling event. Then let's add the following route as shown below:

routes/web.php
Route::get('/t', function () {

    event(new \App\Events\SendMessage());

    dd('Event Run Successfully.');

});


Now we can run our example. However, follow the instructions below to complete your project.

You must install the Redis server on your system or server. Then you cannot install it with the following command:

sudo apt install redis-server

You can then start the Laravel echo server as follows:

laravel-echo-server start

You can now run the project using the following command:

php artisan serve

You can now open the following URL in your browser:

http://localhost:8000/

Now you can photograph your event with this URL:

http://localhost:8000/t


I hope I can help you ...

Using Eloquent Query Scopes with Laravel

Using Eloquent Query Scopes with Laravel


Today I want to give an example of how the scope of the eloquent Laravel model can be used. I'll show you how to create an eloquent model query area in Laravel 6 and how it will be easy for you. I will guide you to create a custom query function in the eloquent model using the 6 range in Laravel.

You can easily use the dynamic query range in the Laravel 6 application.

At some point we will be working on model requests such as retrieving records today, retrieving active records, retrieving prohibited users, etc. At this point, we use whatever condition anywhere in the controller file. I think if the state is correct it is not bad, but you should always write with a login like the current date etc. and again you can use functions like "latest ()". You can easily reuse this area in your model query.

Here I give you a simple range with today () and you only get records today. Let's look at this example here:

Generate Scope in Model


Here we will expand the scope of our publication model today. So if we check the controller, we will use this area in the Laravel model.

app/Post.php
<?php

  

namespace App;

  

use Illuminate\Database\Eloquent\Model;

  

class Post extends Model

{

    public $table = "posts";

      

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'id', 'title', 'body', 'status'

    ];

    /**

     * Scope a query to only include popular users.

     *

     * @param \Illuminate\Database\Eloquent\Builder $query

     * @return \Illuminate\Database\Eloquent\Builder

     */

    public function scopeToday($query)

    {

        return $query->whereDate('created_at', \Carbon\Carbon::today());

    }

}


Use Scope Query


Now you can see how to use that with your driver file.

Post::select("*")->today()->get();


Dynamic Scope in Model


Here we will expand the scope of our publication model today. So if we check the controller, we will use this area in the Laravel model.

app/Post.php
<?php

  

namespace App;

  

use Illuminate\Database\Eloquent\Model;

  

class Post extends Model

{

    public $table = "posts";

      

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    protected $fillable = [

        'id', 'title', 'body', 'status'

    ];

    /**

     * Scope a query to only include popular users.

     *

     * @param \Illuminate\Database\Eloquent\Builder $query

     * @return \Illuminate\Database\Eloquent\Builder

     */

    public function scopeStatus($query, $type)

    {

        return $query->where('status', $type);

    }

}


Use Scope Query


Now you can see how to use that with your driver file.

Post::select("*")->status(1)->get();


I hope this could help you ...

Thursday, February 27, 2020

Install React JS along with Laravel

 Install React JS along with Laravel

Hi Buddies

If you want to know how to install React Js on Laravel 6, I can help you install Laravel React Js with Laravel UI. We will also install React with Laravel and Laravel 6 React Auth with Laravel UI.

If you are a beginner with Laravel 6, I can certainly help you to respond to Laravel 6. This is a very easy way to install using the Laravel Ui Composer package.

Laravel ui offers the possibility to install Bootstrap, to react and to configure the reaction. They also offer an authentication framework for logging in and registering. Laravel 6 provides an easy way to work, respond, and respond with Bootstrap.

If you want to install React in your Laravel 6 project, install the following Laravel UI Composer package to get the command:

composer require laravel/ui

After successfully installing the previous package, we can install and respond to our application.
We can install in two ways: one is a simple installation of the reaction installation and another is a reaction installation with authentication. So let's look in both directions.

Install React Js


php artisan ui react


Install React Js with auth


php artisan ui react --auth


After we install React, you can see your js folder in the resource directory.

You also need to install and run npm. So let's execute both commands:

Install NPM


npm install

Run NPM


npm run dev


Now you can start working with your react application.

I hope this could help you ...

How to Install Bootstrap 4 in Laravel

How to Install Bootstrap 4 in Laravel

Hi Buddies

I want to show you how to install Bootstrap 4 in the Laravel 6 application. We need to install the Laravel UI package to install NPM Bootstrap 4 in Laravel 6. You can do this easily with the npm command with the Laravel 6 Ui package.

If you are a beginner with Laravel 6, I can certainly help you install Bootstrap 4 on Laravel 6. Installation with the Laravel UI Composer package is very easy.

Laravel ui offers a possibility to install the configuration of Bootstrap, Vue and React. They also offer an authentication framework for logging in and registering. Laravel 6 provides an easy way to work, fly and respond with Bootstrap.

If you want to install Bootstrap 4 in your Laravel 6 project, install the following Laravel UI Composer package to get the command:

composer require laravel/ui

After successfully install above package then we are ready to install bootstrap 4 with our application.

we can install two way, one is a simple bootstrap 4 setup install and another is install bootstrap 4 with auth. So let's see both way.

Install Bootstrap 4


php artisan ui bootstrap

Install Bootstrap 4 with auth


php artisan ui bootstrap

Now we install Bootstrap. You can see the js folder of your resource directory.

You also need to install and run npm. So let's execute both commands:

Install NPM


npm install

Run NPM


npm run dev


Now you can start working with your Bootstrap 4 application.

I hope this could help you ...

Wednesday, February 26, 2020

How Global Scope works in Laravel?

How Global Scope works in Laravel?

Hi Buddies,

In this tutorial, I want to show you how to define global reach in Laravel and how to use global reach in Laravel 6 application. I'll show you how to create a global reach in Laravel and how to remove a global reach in Laravel.

Global Scope is a very important concept of Laravel 6. The use of Global Scope can reuse the same eloquent condition when using Laravel. I also wrote a tutorial on how to create a local area in Laravel 6. The local area only applies to a single model. However, if you define the global reach, you can use it with all models.


In this example, we create ActiveScope to retrieve only active records of the model. Use with multiple models in the same range. You can check this step by step:

Create Global Scope File


In this step, we create a new global ActiveScope range class as follows:

app\Scopes\ActiveScope.php
<?php


  


namespace App\Scopes;


  


use Illuminate\Database\Eloquent\Builder;


use Illuminate\Database\Eloquent\Model;


use Illuminate\Database\Eloquent\Scope;


  


class ActiveScope implements Scope


{


    /**


     * Apply the scope to a given Eloquent query builder.


     *


     * @param  \Illuminate\Database\Eloquent\Builder  $builder


     * @param  \Illuminate\Database\Eloquent\Model  $model


     * @return void


     */


    public function apply(Builder $builder, Model $model)


    {


        $builder->where('is_active', '=', 1);


    }


}


Define Global Scope in User Model


Here we are going to expand our user model today. So if we check the controller, we will use this area in the Laravel model.

app/User.php
<?php


  


namespace App;


  


use Illuminate\Database\Eloquent\Model;


use App\Scopes\ActiveScope;


  


class User extends Model


{


    protected $fillable = [


        'name','email','password','is_active',


    ];


  


    protected static function boot()


    {


        parent::boot();


  


        static::addGlobalScope(new ActiveScope);


    }


}


Define Global Scope in Admin Model


Here we will expand our admin model today. So if we check the controller, we will use this area in the Laravel model.

app/Admin.php
<?php


  


namespace App;


  


use Illuminate\Database\Eloquent\Model;


use App\Scopes\ActiveScope;


  


class Admin extends Model


{


    protected $fillable = [


        'name','email','password','is_active',


    ];


  


    protected static function boot()


    {


        parent::boot();


  


        return static::addGlobalScope(new ActiveScope);


    }


}


Get Active Records:


Now you can see how to use that with your driver file.

You will only receive active data records with the following queries:


$users = User::select('*')->get();


  


$admins = Admin::select('*')->get();



Get All Records:


You only add records with the following queries from the user and administrator table:

$users = User::select('*')->withoutGlobalScope(ActiveScope::class)->get();


  


$admins = Admin::select('*')->withoutGlobalScope(ActiveScope::class)->get();


I hope This Could help you ...

How to show Log Query in Laravel 6?

How to show Log Query in Laravel 6?

At some point we have to print the last query executed in the Laravel 6 application to debug it. You want to see which last query was run. I will give examples of how to print the login session in Laravel 6. You can simply print the last eloquent query in Laravel 6.

I will print the last SQL query in Laravel 6 with toSql (), DB :: enableQueryLog () and DB :: getQueryLog (). I will also show you the output of the SQL print query.

So let's look at the following examples and use them as you wish.

Example 1:


Controller Code:

$query = User::select("*")->toSql();

dd($query);

Output:

select * from `users`


Example 2:


Controller Code:

DB::enableQueryLog();

$users = User::select("*")->get();

$quries = DB::getQueryLog();

dd($quries);

Output:

array:1 [▼

0 => array:3 [▼

"query" => "select * from `users`"

"bindings" => []

"time" => 4.25

]

]


Example 3:


Controller Code:

DB::enableQueryLog();

  

$users = User::select("*")->get();

$query = DB::getQueryLog();

$query = end($query);

dd($query);

Output:

array:3 [▼

"query" => "select * from `users`"

"bindings" => []

"time" => 2.07

]


I hope This Could help you ...

Friday, February 21, 2020

How to add ckeditor with image upload in Laravel ?

How to add ckeditor with image upload in Laravel


Today I wanted to give you an example of using ckeditor in Laravel 6 and ckeditor with loading images in the Laravel 6 application. You need to follow the 4 steps to install ckeditor in Laravel 6 and upload images to Ckeditor with Laravel 6.

You can also preview image loading in ckeditor with Laravel 6.

We will use the filebrowseruploadurl and filebrowserUploadMethod functions from ckeditor in laravel 5. If loading ckeditor images in laravel does not work, I will explain how to load the image with ckeditor in laravel.

I am writing a very simple example of gradually loading images with Laravel so that you can easily use it in your Laravel. Ckeditor is the most powerful content editor tool. So if you have the ability to load images as well, this is amazing.

So let's take a look at the following steps to load images into ckeditor laravel.


Step 1: Add Routes


First we need to create two paths to display the ckeditor form page and another to load images. So let's do it.

routes/web.php
Route::get('ckeditor', 'CkeditorController@index');

Route::post('ckeditor/upload', 'CkeditorController@upload')->name('ckeditor.upload');



Step 2: Create Controller


In this step we create a new controller like CkeditorController with two index () and upload () methods. In the index method we return and see the upload method and write the image upload code.

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

  

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

  

class CkeditorController extends Controller

{

    /**

     * success response method.

     *

     * @return \Illuminate\Http\Response

     */

    public function index()

    {

        return view('ckeditor');

    }

  

    /**

     * success response method.

     *

     * @return \Illuminate\Http\Response

     */

    public function upload(Request $request)

    {

        if($request->hasFile('upload')) {

            $originName = $request->file('upload')->getClientOriginalName();

            $fileName = pathinfo($originName, PATHINFO_FILENAME);

            $extension = $request->file('upload')->getClientOriginalExtension();

            $fileName = $fileName.'_'.time().'.'.$extension;

        

            $request->file('upload')->move(public_path('images'), $fileName);

   

            $CKEditorFuncNum = $request->input('CKEditorFuncNum');

            $url = asset('images/'.$fileName); 

            $msg = 'Image uploaded successfully'; 

            $response = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";

               

            @header('Content-type: text/html; charset=utf-8'); 

            echo $response;

        }

    }

}



Step 3: Create Blade File


Here we need to create the ckeditor.blade.php file and write form logic and ckeditor js code. So let's do it.

resources/views/ckeditor.blade.php
<!DOCTYPE html>

<html>

<head>

    <title>Laravel 6 Ckeditor Image Upload Example - ItSolutionStuff.com</title>

    <script src="https://cdn.ckeditor.com/4.12.1/standard/ckeditor.js"></script>

</head>

<body>

  

<h1>Laravel 6 Ckeditor Image Upload Example - ItSolutionStuff.com</h1>

<textarea name="editor1"></textarea>

   

<script type="text/javascript">

    CKEDITOR.replace('editor1', {

        filebrowserUploadUrl: "{{route('ckeditor.upload', ['_token' => csrf_token() ])}}",

        filebrowserUploadMethod: 'form'

    });

</script>

   

</body>

</html>


Step 4: Create images folder


In the last step we have to create the folder "images" in your public directory. Then it has to be created with permission.

Now we can run our application example with Laravel 6. Therefore, run the following command for quick execution:

php artisan serve

http://localhost:8000/ckeditor

I hope this could help you ...



How to paginate Laravel collection ?


How to paginate Laravel collection ?

In this tutorial, I want to show you how to create a pagination from an array or collection object in the Laravel 6 application. We create a Laravel 6 pagination from the matrix example. This example helps create a paginated collection object in Laravel 6.

We will create our custom collection object with matrix and create a pagination with eloquent laravel. We will use the Paginator and LengthAwarePaginator facade to create a pagination from a custom matrix in Laravel 6.

In this example, we simply create a route and call the controller method. This controller method creates our custom matrix and makes it a collection object. We also create a paginate () on the same controller to create a pagination in Laravel 6. Then all you have to do is call view and pass the result variable. You can use as a paginated object.

So let's take a look at the following example step by step.

Create Route


In the next step we add a new path to the web.php file. route we call the controller method So we just create both routes as described below:

routes/web.php
Route::get('paginate', 'PaginationController@index');


Create Controller


Here we create PaginationController using two methods, one for the call route and the other for creating a custom page. Let's add the controller as follows:

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

  

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

use Illuminate\Pagination\Paginator;

use Illuminate\Support\Collection;

use Illuminate\Pagination\LengthAwarePaginator;

  

class PaginationController extends Controller

{

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    public function index()

    {

        $myArray = [

            ['id'=>1, 'title'=>'Laravel 6 CRUD'],

            ['id'=>2, 'title'=>'Laravel 6 Ajax CRUD'],

            ['id'=>3, 'title'=>'Laravel 6 CORS Middleware'],

            ['id'=>4, 'title'=>'Laravel 6 Autocomplete'],

            ['id'=>5, 'title'=>'Laravel 6 Image Upload'],

            ['id'=>6, 'title'=>'Laravel 6 Ajax Request'],

            ['id'=>7, 'title'=>'Laravel 6 Multiple Image Upload'],

            ['id'=>8, 'title'=>'Laravel 6 Ckeditor'],

            ['id'=>9, 'title'=>'Laravel 6 Rest API'],

            ['id'=>10, 'title'=>'Laravel 6 Pagination'],

        ];

  

        $myCollectionObj = collect($myArray);

  

        $data = $this->paginate($myCollectionObj);

   

        return view('paginate', compact('data'));

    }

   

    /**

     * The attributes that are mass assignable.

     *

     * @var array

     */

    public function paginate($items, $perPage = 5, $page = null, $options = [])

    {

        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

        $items = $items instanceof Collection ? $items : Collection::make($items);

        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);

    }

}


Create View File


Here we just have to create a blade file to print data. Therefore, we create a simple blade file like the following:

app/Http/Controllers/PaginationController.php
<div class="container">

    <table class="table table-bordered">

        <tr>

            <th>Id</th>

            <th>Title</th>

        </tr>

        @foreach($data as $post)

        <tr>

            <td>{{ $post->id }}</td>

            <td>{{ $post->title }}</td>

        </tr>

        @endforeach

    </table>

</div>

   

{{ $data->links() }}


Now you can run and check.

I hope this could help you ...


Thursday, February 20, 2020

Laravel 6 ACL Roles and Permissions Tutorials

Laravel 6 ACL Roles and Permissions Tutorials

The main topic today is the creation of Laravel 6 roles and tutorial permissions from scratch. We're going to create Laravel 6 Acl with the Spatie Laravel permission pack. I have written a step-by-step guide to the Laravel 6 privilege and user role authentication module.

You only need to take a few steps to complete Laravel 6 roles and authentication credentials. So let's follow this tutorial step by step.

The Composer package for Spatie role permissions provides a way to create Acl in Laravel 6. They include information about assigning roles to users, assigning permissions to users, and assigning permissions to roles. I will write step by step to create roles and permissions in the Laravel 6 application.

Roles and permissions allow you to create different types of users with different roles and permissions, i.e. some users only see the element list module, some users can also edit, delete element modules, etc.

In these examples, I created three modules as listed below:

user management
role management
product management


After the user has registered, he has no role, so you can edit his details and assign an administrator role via the user administration. You can then create your own function with authorization such as function list, function creation, function processing, function elimination, product list, product creation, product processing, product disposal. You can check this by assigning a new user and checking this.

You just need to do a few steps and get a complete example of ACL:

Step 1: Laravel 6 Installation


We go from scratch. If you don't have Laravel installed on your system, you can run the following command and get a new project from Laravel.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install Composer Packages


Now we have to install the ACL Spatie package so that we can use its method. We will also install the form collection package. Then open your terminal and run the following command.

composer require spatie/laravel-permission
composer require laravelcollective/html

Now open the file config / app.php and add the service provider and the alias.

config/app.php
'providers' => [

....

Spatie\Permission\PermissionServiceProvider::class,

],


We can also adapt the changes in the Spatie package. So if you also want to make changes, you can activate the following command and call up the configuration file in config / allow.php and the migration files.

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

Now you can see the allow.php file and a migration. So you can perform the migration with the following command:

php artisan migrate

Monday, February 17, 2020

How to Create Routes in Laravel 6-Easy Tutorial

How to Create Routes in Laravel 6-Easy Tutorial

Today in this tutorial I will explain the Laravel routing tutorial step by step. We will learn how to create a new route in Laravel. You can easily create a later path in the Laravel application. I will also show how to create a route in the Laravel controller.

Let us see step by step how to create the first route in Laravel and understand the Laravel routing shortly.

What is Laravel Routing?


With routing, you can create a request URL for your application. You can design an HTTP request set as a POST request, GET request, PUT request, and DELETE request using Laravel routing.

You can simply create a route in the web.php file in a route folder. You can create your route list in various ways in the web.php file. I will show you step by step how to create it and how it works. So let's see a step-by-step explanation.

Create Simple Route:


Here we create a very simple route and tell you how to access it. So let's create a simple route with the following line by adding the path file:

routes/web.php

Route::get('simple-route', function () {

    return 'This is Simple Route Example of ItSolutionStuff.com';

});

Access URL:

http://localhost:8000/simple-route


Route with Call View File:


You can create a route directly from the route using the Call View Blade file. You can see the following route example:

routes/web.php

Route::view('my-route', 'index');

resources/views/index.php

Route::view('my-route', 'index');

Access URL:

http://localhost:8000/my-route

Route with Controller Method:


Now you can create a route using the call controller method. So you can simply create the controller method and call this method with your route as follows:

routes/web.php

Route::get('my-route', 'TestController@index');

app/Http/Controllers/TestController.php

<?php

  

namespace App\Http\Controllers;

  

class TestController extends Controller

{

  

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Contracts\Support\Renderable

     */

    public function index()

    {

        return view('index');

    }

}

resources/views/index.php

<h1>his is Simple Route Example of ItSolutionStuff.com</h1>

Access URL:

http://localhost:8000/my-route


Create Route with Parameter:


Here we create a simple route with step parameters. You can create a dynamic route with your controller. So let's create as follows.

routes/web.php

Route::get('users/{id}', 'UserController@show');

app/Http/Controllers/UserController.php

<?php

  

namespace App\Http\Controllers;

  

class UserController extends Controller

{

  

    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Contracts\Support\Renderable

     */

    public function show($id)

    {

        return 'User ID:'. $id;

    }

}

Access URL:

http://localhost:8000/users/21

Create Route Methods:


You can use the methods below to get, publish, delete, set, and patch paths. You can understand how it works.

So let's look at the following examples of routes:

Route::get('users', 'UserController@index');

Route::post('users', 'UserController@post');

Route::put('users/{id}', 'UserController@update');

Route::delete('users/{id}', 'UserController@delete');

You can also check how many routes I created using the following command:

php artisan route:list


You can see the list of all routes.

I hope This Could help you...