Category Archives: Laravel Tutorial

Laravel Facades


Laravel Facades – The Laravel facades serve as “static proxies” to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.


Laravel Facades.

Let us understand how to use laravel Facades.

Function:-

There are some followings function available in laravel Facades.

  • 1. Introduction.
  • 2. When To Use Facades.
  • 3. How Facades Work.
  • 4. Facade Class Reference.

1. Introduction.

Facades provide a “static” interface to classes that are available in the application’s service container. Laravel ships with many facades which provide access to almost all of Laravel’s features.

All of Laravel’s facades are defined in the Illuminate/Support/Facades namespace. So, we can easily access a facade like this:

Let’s look at a simple example.

use Illuminate\Support\Facades\Cache;
Route::get('/cache', function () {
    return Cache::get('key');
});

2. When To Use Facades.

Facades have more advantage. They provide a brief, memorable syntax that allows to use Laravel features without memorize lonf class names that must be injected or configured manually. Because of their unique usage of PHP’s dynamic methods, they are easy to test.

The primary danger of facades is class scope creep. Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class.

When building a third party package that interacts with laravel, it’s better to inject Laravel contracts instead of using facades. Since packages are built outside of Laravel itself, you will not have access to Laravel’s facade testing helper.

Facades Vs. Dependency Injection

One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub.

Typically, it would not be possible to mock or stub a truly static class method. However, since facades use dynamic methods to proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance.

Let’s look at a simple example.

use Illuminate\Support\Facades\Cache;

Route::get('/cache', function () {
    return Cache::get('key');
});

We can write the following test to verify that the cache::get method was called with the argument.

Let’s look at a simple example.

use Illuminate\Support\Facades\Cache;

public function testBasicExample()
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $this->visit('/cache')
         ->see('value');
}

Facades Vs. Helper Functions

Laravel includes a variety of “helper” functions which can perform common tasks like generating views, firing events, dispatching jobs, or sending HTTP responses. Many of these helper functions perform the same function as a corresponding facade.

return View::make('profile');

return view('profile');

There is no difference between facades and helper function. When using helper functions, you may still test them exactly as you want to corresponding facades.

Route::get('/cache', function () {
    return cache('key');
});

The cache helper is going to call the get method on the class underlying the cache facades. So, even though we are using the helper function, we can write the following test to verify that the method was called with the argument we expected:

Let’s look at a simple example.

use Illuminate\Support\Facades\Cache;

public function testBasicExample()
{
    Cache::shouldReceive('get')
         ->with('key')
         ->andReturn('value');

    $this->visit('/cache')
         ->see('value');
}

3. How Facades Work.

A facade is a class that provide access to an object from the container. The machinery that makes this work is in the facade class. Laravel’s facades, and any custom facades you create, will extend the base Illuminate/Support/Facades/Facade class.

The Facade base class make use of the __callStatic() magic-method to defer calls from your facade to an object resolved from the container.

Let’s look at a simple example.

 $user]);
    }
}

Notice that near the top of the file we are “importing” the cache facade. This facade serves as a proxy to accessing the underlying implementation of the Illuminate/Contracts/Cache/Factory nterface. Any calls we make using the facade will be passed to the underlying instance of Laravel’s cache service.

Let’s look at a simple example.

class Cache extends Facade
{
   
    protected static function getFacadeAccessor() { return 'cache'; }
}

Instead, the cache facade extend the base facade class and defines the method getFacadeAccessor(). This method’s job is to return the name of a service container binding.

4. Facade Class Reference.

Below you will find every facade and its underlying class. This is a useful tool for quickly digging into the API documentation for a given facade root. The Service Container Binding key is also included where applicable.

Facade Class Service Container Binding
App Illuminate/Foundation/Application app
Artisan Illuminate/Contracts/Console/Kernel artisan
Auth Illuminate/Auth/AuthManager auth
Blade Illuminate/View/Compilers/BladeCompiler blade.compiler
Bus Illuminate/Contracts/Bus/Dispatcher
Cache Illuminate/Cache/Repository cache
Config Illuminate/Config/Repository config
Cookie Illuminate/Cookie/CookieJar Cookie
Crypt Illuminate/Encryption/Encrypter encrypter
DB Illuminate/Database/DatabaseManager db
DB (Instance) Illuminate/Database/Connection
Event Illuminate/Event/Dispatcher events
File Illuminate/FileSystem/FileSystem files
Gate Illuminate/Contracts/Auth/Access/Gate
Hash Illuminate/Contracts/Hashing/Hasher hash
Lang Illuminate/Translation/translator translator
Log Illuminate/Log/Writer log
Mail Illuminate/Mail/Mailer mailer
Notification Illuminate/Notifications/ChannelManager mailer
Password Illuminate/Auth/Passwords/PasswordBrokermanager auth.password
Queue Illuminate/Queue/QueueManger queue
Queue (Instance) Illuminate/Contracts/Queue/Queue queue
Queue (Base Class) Illuminate/Queue/Queue
Redirect Illuminate/Routing/Redirector redirect
Redis Illuminate/Redis/Database redis
Request Illuminate/Http/Request Request
Response Illuminate/Contracts/Routing/ResponseFactory
Route Illuminate/Routing/Router router
Schema Illuminate/Database/Schema/BluePrint
Session Illuminate/Session/SessionManager session
Session (Instance) Illuminate/Session/Store
Storage Illuminate/Contracts/Filesystem/Factory filesystem
URL Illuminate/Routing/UrlGenerator url
Validator Illuminate/validation/Factory validator
Validator (Instance) Illuminate/validation/Validator
View Illuminate/View/Factory view
View (Instance) Illuminate/View/View

Laravel Service Providers


Laravel Service Providers – The Laravel service Providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services, are bootstrapped through service providers.


Laravel Service Providers.

Let us understand how to use laravel service Providers.

Function:-

There are some followings function available in laravel service Providers.

  • 1. Introduction.
  • 2. Writing Service Providers.
  • 3. Registering Providers.
  • 4. Deferred Providers.

1. Introduction.

All laravel core services are bootstrapped through service providers.

But, what do we mean by “bootstrapped”? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

If you open the config/app.php file included with Laravel, you will see a providers array. These are all of the service provider classes that will be loaded for your application. Of course, many of these are “deferred” providers, meaning they will not be loaded on every request, but only when the services they provide are actually needed.

In this overview you will learn how to write your own service providers and register them with your Laravel application.

2. Writing Service Providers.

All service providers extend the Illuminate/Support/ServiceProvider class. Most service providers contain a register and a boot method. Within the register method. You should only blind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method.

The Artisan CLI can generate a new provider through the make:provider command.

php artisan make:provider RiakServiceProvider

The Register Method

Within the register method, you should only blind thing into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method. Otherwise, you may accidentally use a service that is provided by a service provider which has not loaded yet.

Let’s look at a simple example.

app->singleton(Connection::class, function ($app) 
        {
            return new Connection(config('riak'));
        });
    }
}

This service provider only defines a register method, and uses that method to define an implementation of Riak/connection in the service container.

The Boot Method

So, what if we need to register a view composer within our service provider? This should be done within the boot method. This method called after all other service providers have been registered.

Let’s look at a simple example.

composer('view', function () {
            //
        });
    }
}

Boot Method Dependency Injection

You may type-hint dependencies for your service provider’s boot method. The service container will automatically inject any dependencies you need.

Let’s look at a simple example.

use Illuminate\Contracts\Routing\ResponseFactory;
public function boot(ResponseFactory $response)
{
    $response->macro('caps', function ($value) {
        //
    });
}

3. Registering Providers.

All service providers are registered in the config/app.php configuration file. This file contains a providers array where you can list the class names of your service providers. By default, a set of Laravel core service providers are listed in this array. These providers bootstrap the core Laravel components, such as the mailer, queue, cache, and others.

To register your provider, simply add it to the array.

'providers' => [
 // Other Service Providers
 App\Providers\ComposerServiceProvider::class,
],

4. Registering Providers.

If your provider is only registering bindings in the service container, you may choose to defer its registration until one of the registered bindings is actually needed. Deferring the loading of such a provider will improve the performance of your application since it is not loaded from the filesystem on every request.

Laravel compiles and stores a list of all of the services supplied by deferred service providers, along with the name of its service provider class. Then, only when you attempt to resolve one of these services does Laravel load the service provider.

To defer the loading of a provider, set the defer property to true and define a provides method. The provides method should return the service container bindings registered by the provider.

Let’s look at a simple example.

app->singleton(Connection::class, function ($app) {
            return new Connection($app['config']['riak']);
        });
    }
    public function provides()
    {
        return [Connection::class];
    }
}

Laravel Service Container


Laravel Service Container – The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection.


Laravel Service Container.

Let us understand how to use laravel service container.

Function:-

There are some followings function available in laravel service container.

  • 1. Introduction.
  • 2. Binding.
  • 3. Resolving.
  • 4. Container Events.

1. Introduction.

It is a powerfull tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.

Let’s look at a simple example.

users = $users;
    }

    public function show($id)
    {
        $user = $this->users->find($id);

        return view('user.profile', ['user' => $user]);
    }
}

The UserController needs to retrieve users from a data source. So, we will inject a service that is able to retrieve users. In this context our, UserRepository most likely uses Eloquent to retrieve user information from the database.

A deep understanding of the Laravel service container is essential to building a powerful, large application, as well as for contributing to the Laravel core itself.

2. Binding.

Binding Basics

Almost all of your service container bindings will be registered within Service Providers, so most of these examples will demonstrate using the container in that context.

Simple Bindings

Within a service provider, you can access to the container through the $this->app
property. We can register a binding using the bind method, passing the class or interface name that we wish to register along with a closure that returns an instance of the class

$this->app->bind('HelpSpot\API', function ($app) 
{
    return new HelpSpot\API($app->make('HttpClient'));
}
);

Note that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building.

Binding A Singleton

The singleton method binds a class or interface into the container that should only be resolved one time. Once a singleton binding is resolved, the same object instance will be returned on subsequent calls into the container.

$this->app->singleton('HelpSpot\API', function ($app) 
{
    return new HelpSpot\API($app->make('HttpClient'));
}
);

Binding Instances

You can also bind an existing object instance into the container using the instance method. The given instance will always be returned on subsequent calls into the container.

$api = new HelpSpot\API(new HttpClient);
$this->app->instance('HelpSpot\Api', $api);

Binding Primitives

Sometimes you may have a class that receives some injected classes but also needs an injected primitive value such as an integer. You can easily use contextual binding to inject any value your class may need

$this->app->when('App\Http\Controllers\UserController')
          ->needs('$variableName')
          ->give($value);

Binding Interfaces To Implementations

A very powerful feature of the service container is its ability to bind an interface to a given implementation. For example, suppose we have an EventPusher interface and a RedisEventPusher implementation. Once we have coded our RedisEventPusher implementation of this interface, we can register it with the service container like this:

$this->app->bind
(
    'App\Contracts\EventPusher',
    'App\Services\RedisEventPusher'
);

Now we can type-hint the EventPusher interface in a constructor, or any other location where dependencies are injected by the service container.

Let’s look at a simple example.

use App\Contracts\EventPusher;
public function __construct(EventPusher $pusher)
{
    $this->pusher = $pusher;
}

Contextual Binding

Sometimes you may have two classes that utilize the same interface, but you wish to inject different implementations into each class. For example, two controllers may depend on different implementations of the Illuminate/Contracts/Filesystem/Filesystem Contracts.

Let’s look at a simple example.

use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\PhotoController;
use App\Http\Controllers\VideoController;
use Illuminate\Contracts\Filesystem\Filesystem;

$this->app->when(PhotoController::class)
          ->needs(Filesystem::class)
          ->give(function () {
              return Storage::disk('local');
          });

$this->app->when(VideoController::class)
          ->needs(Filesystem::class)
          ->give(function () {
              return Storage::disk('s3');
          });

Tagging

You may need to resolve all of a certain “category” of binding. For example, perhaps you are building a report aggregator that receives an array of many different Report interface implementations. After registering the Report implementations, you can assign them a tag using the Tag method.

Let’s look at a simple example.

$this->app->bind('SpeedReport', function () 
{
    //
});

$this->app->bind('MemoryReport', function () 
{
    //
});

$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');

Once the services have been tagged, you may easily resolve them all via the tagged method.

$this->app->bind('ReportAggregator', function ($app) 
{
    return new ReportAggregator($app->tagged('reports'));
});

3. Resolving.

The make command

You may use the make method to resolve a class instance out of the container. The make method accepts the name of the class or interface you wish to resolve.

$api = $this->app->make('HelpSpot\API');

If you are in a location of your code that does not have access to the $app variable, you may use the global resolve helper.

$api = resolve('HelpSpot\API');

Automatic Injection

Alternatively, and importantly, you may simply “type-hint” the dependency in the constructor of a class that is resolved by the container, including Controllers, event listeners, queue jobs and middleware and more.

For example, you can type-hint a repository defined by your application in a controller’s constructor. The repository will automatically be resolved and injected into the class

Let’s look at a simple example.

users = $users;
    }
    public function show($id)
    {
        //
    }
}

4. Container Events.

The service container fires an event each time it resolves an object. You may listen to this event using the resolving methods.

Let’s look at a simple example.

$this->app->resolving(function ($object, $app) 
{
    // ...
});

$this->app->resolving(HelpSpot\API::class, function ($api, $app) 
{
    // ...
});

As we can see, the object being resolved will be passed to the callback, allowing you to set any additional properties on the object before it is given to its consumer.

Laravel Request Lifecycle Process


Laravel Request Lifecycle Process – The Goal of request lifecycle process is to give you a good, high-level overview of how the Laravel framework works.


Laravel Request Lifecycle Process.

Let us understand how to Work laravel Framework.

Functions:-

There are some followings function available in laravel request lifecycle process.

  • 1. Introduction.
  • 2. Lifecycle Overview.
  • 3. Focus On Service Providers.

1. Introduction.

When using any tool in the “real world”, you feel more confident if you understand how that tool works. Application development is no different. When you understand how your development tools function, you feel more comfortable and confident using them.

The goal of this document is to give you a good, high-level overview of how the Laravel framework works. By getting to know the overall framework better. If you don’t understand all the concept, Don’t lose heart! Just try to get a basic concept of what is going on, and your knowledge will grow as you explore other sections of the documentation.

2. Lifecycle Overview.

First Things

The entry point for all requests to a Laravel application is the public/index.php file. All requests are directed to this file by your web server (Apache / Nginx) configuration. The index.php file doesn’t contain much code. Rather, it is simply a starting point for loading the rest of the framework.

The index.php file loads the Composer generated autoloader definition, and then retrieves an instance of the Laravel application from bootstrap/app.php script.

HTTP / Console Kernels

The incoming request is sent to either the HTTP kernel or the console kernel, depending on the type of request that is entering the application. These two kernels serve as the central location that all requests flow through. For now, let’s just focus on the HTTP kernel, which is located in app/Http/kernel.php.

The HTTP kernel extends the Illuminate\Foundation\http\Kernel class, which defines an array of bootstrapers that will be run before the request is executed.

Service Providers

Kernel bootstrapping actions is loading the service providers for your application. All of the service providers for the application are configured in the config/app.php configuration file’s providers array. First, the register method will be called on all providers, then, once all providers have been registered, the boot method will be called.

Dispatch Request

The application has been bootstrapped and all service providers have been registered, the Request will be handed off to the router for dispatching. The router will dispatch the request to a route or controller, as well as run any route specific middleware.

How To Work Laravel Life Cycle.
Laravel Request Lifecycle Process

3. Focus On Service Providers.

Service providers are truly the key to bootstrapping a Laravel application. The application request is created, the service providers are registered, and the request is handed to the bootstrapped application. It’s really that simple.

How a Laravel application is built and bootstrapped via service providers is very valuable. Of course, your application’s default service providers are stored in the app/providers directory.

By default, the AppServiceProvider is fairly empty. This provider is a great place to add your application’s own bootstrapping and service container bindings. Of course, for large applications, you may wish to create several service providers, each with a more granular type of bootstrapping.

Laravel Valet


Laravel Valet – Laravel Valet is used to provide development environment for Mac minimalists.


Laravel Valet.

Let us understand how to use laravel Valet.

Function:-

There are some followings function available in laravel Valet.

  • 1. Introduction.
  • 2. Installation.
  • 3. Serving Sites.
  • 4. Sharing Sites.
  • 5. Custom Valet Drivers.
  • 6. Other Valet Commands.

1. Introduction.

Valet is a Laravel development environment for Mac minimalists. No Vagrant, no /etc/hosts/ file.

Laravel valet configures your Mac to always run Nginx in the background when your machine starts. Then, using DnsMasq, valet proxies all requests on the *.dev domain to point to sites installed on your local machine.

In other words, a very fast Laravel development environment that uses roughly 7 MB of RAM. Valet isn’t a complete replacement for Vagrant or Homestead, but provides a great alternative if you want flexible basics, prefer extreme speed, or are working on a machine with a limited amount of RAM.

Out of the box, Valet support includes, but is not limited to:

Laravel

Lumen

Symfony

Zend

CakePHP 3

WordPress

Bedrock

Craft

Statamic

Jigsaw

Static Html

However, you may extend Valet with your own Custom Drivers.

Valet Or Homestead

Homestead and Valet both differ in regards to their plan audience and their approach to local development. Homestead offers an entire Ubuntu virtual machine with automated Nginx configuration. Homestead is a wonderful choice if you want a fully virtualized Linux development environment or are on Windows / Linux.

Valet only supports Mac and requires you to install PHP and a database server directly onto your local machine. Valet provides a blazing fast local development environment with minimal resource consumption, so it’s great for developers who only require PHP / MySQL and do not need a fully virtualized development environment.

Both Valet and Homestead are great choices for configuring your Laravel development environment. Which one you choose will depend on your personal taste and your team’s needs.

2. Installation.

Valet requires macOS and Homebrew. Before installation, you should make sure that no other program such as Apache or Nginx are binding to your local machine.
– Install or update Homebrew to the latest version using brew update.
– Install PHP 7.1 using Homebrew via brew install homebrew/php/php7.1.
– Install Valet with composer via Composer global require laravel/valet.
– Run the valet install command. This command will configure and install your valet and DnsMasq and register valet daemon to launvh when your system starts.

Using Another Domain

By default, valet provide your project using the .dev TLD. If you want to use another domain, you can do using the valet domain tld-name command.

Database

If you need a database, to use MYSql by running brew install mysql on your command line. Once MySql has been installed, then you can start it using by brew services start mysql command. Then you can connect to the database at 127.0.0.1 using username is root and password is empty string.

Upgrading

You may update your valet installation using the composer global update command in your terminal.

Upgrading To Valet 2.0

Valet 2.0 transitions Valet’s underlying web server from Caddy to Nginx. Before upgrading to this version you should run the following commands to stop and uninstall the existing Caddy daemon

valet stop
valet uninstall

Now like this you should update to the latest version of valet through composer.

composer global require laravel/valet

Once the fresh valet source code has been downloaded, you should run the install command.

valet install
valet restart

3. Serving Sites.

Once Valet is installed, you are ready to start serving sites. Valet provides two commands to help you serve your Laravel sites which is Park and Link.

The park command.

Create a new directory on your Mac by running something like mkdir ~/Sites. Next,cd ~/Sites and run valet park. This command will register your current working directory as a path that Valet should search for Sites.

Next, create a new laravel site within this directory:laravel new blog.

Open http://blog.dev in your browser.

The link command.

The link command is also used to serve your Laravel site. If you want to serve a single site in a directory and not the entire directory.

To run valet link app-name in your terminal. Valet will create a symbolic link in ~/.valet/Sites which points to your current working directory.

After running the Link command, you can access the site in your browser at http://app-name.dev.

You can use valet unlink app-name to destroy the symbolic link.

4. Sharing Sites.

Valet even includes a command to share your local sites with the world. No additional software installation is required once Valet is installed.

To share a site, navigate to the site’s directory in your terminal and run the valet share command.

To stop sharing your site, hit control + c to cancel the process.

5. Custom Valet Drivers.

You can write your own Valet “driver” to serve PHP applications running on another framework or CMS that is not natively supported by Valet. When you install Valet, a ~/.valet/Drivers directory is created which contains a SampleValetDriver.php file. Writing a driver only requires you to implement three methods serves, isStaticFile and frontControllerPath.

All three methods receive the $sitePath, $siteName and $uri values as their arguments. The $siteName is the fully qualify path to teh site being served on your machine, such as Users/SolidCoupon/Site/My-project. The $siteName is the “Host”/”siteName” portion of the domain {My-project}. The $uri is the incoming request URI (/foo/bar).

The Serves Method

The serve method should return true if your driver should handle the incoming request. Otherwise the method should return false. So, within this method you should attempt to determine if the given $sitePath contains a project of the type you are trying to serve.

public function serves($sitePath, $siteName, $uri)
{
    return is_dir($sitePath.'/wp-admin');
}

The isStaticFile Method

The isStaticFile should determine if the incoming request is for a file that is “static”, such as an image or a stylesheet. If the file is static, the method should return the fully qualified path to the static file on disk. If the incoming request is not for a static file, the method should return false.

public function isStaticFile($sitePath, $siteName, $uri)
{
    if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) {
        return $staticFilePath;
    }

    return false;
}

The frontControllerPath Method

The frontControllerPath method should return the fully qualified path to your application’s “front controller”, which is typically your “index.php” file or equivalent.

public function frontControllerPath($sitePath, $siteName, $uri)
{
    return $sitePath.'/public/index.php';
}

6. Other Valet Commands.

Laravel Valet

Laravel Homestead


Laravel Homestead – Laravel Homestead is used to provide you a wonderfull development enviroment without requiring you to install PHP, a web server and any other server software on your local machine..


Laravel Homestead.

Let us understand how to use laravel homestead.

Function:-

There are some followings function available in laravel homestead.

  • 1. Introduction.
  • 2. Installation & Setup.
  • 3. Daily Usage.
  • 4. Network Interfaces.
  • 5. Updating Homestead.
  • 6. Old Versions.
  • 7. Provider Specific Settings.

1. Introduction.

Laravel strives to make the entire php development experience delightful, including your local development enviroment.

Laravel homestead is an official, pre packaged vagrant box that provides you a wonderfull development enviroment and no need to install php and other software on your machine. No more worrying about messing up your operating system. Vagrant boxes are completely disposable. If something goes wrong, you can destroy and re-create the box in minutes.

Homestead runs on any windows, MAC or linux system and includes the Nginx web server, PHP 7.1, MySql, Postgres, Redis, Memcached, Node and all of the other goodies you need to develop amazing Laravel applications.

Included software

Ubuntu 16.04
Git
PHP 7.1
Ngnix
MySql
MariaDB
Sqlite3
Postgres
Composer
Node
Redis
Memcached
Beanstalkd
Mailhog
ngrok

2. Installation & Setup.

First Steps

Before launching you Homestead enviroment, you must install Virtualbox5.1, Vmware or Parallels as well as Vagrant. All of these software packages provide easy to use visual installer for all popular operating systems.

To use the VMware provide, you will need to purchase both VMware fusion/ Workstation and the VMware Vagrant plug-in. Through it is not free, VMware can provide faster shared folder performance out of the box.

To use the parallel provider, you have to need to install parallels Vagrant plug-in. It is free to charge.

Installing the homestead vagrant box

VirtualBox/ VMware and Vagrant have been installed, you should add the laravel/homestead box to your vagrant installation using these command. It will take a few minutes to download the box.

vagrant box add laravel/homestead

Installing Homestead

You can install Homestead by simply create a clone the storage. Consider clone the storage into a Homestead folder within your home directory.

cd ~

git clone https://github.com/laravel/homestead.git Homestead

You should check out a tagged version of homestead.

cd Homestead

git checkout v4.0.5

Once you have cloned the homestead repository, run the bash init.sh command from the homestead directory to create the homestead.yaml configuration file. The homestead.yaml file will be placed in the homestead directory.

bash init.sh

init.bat

Configuring Homestead

Setting Your Provider

The provider key in your Homestead.yaml file indicates which vagrant provider should be used.
You may set to the provider you prefer.

provider: virtualbox

Configuring Shared Folders

The folder property of the Homestead.yaml file lists all of the folders you want to share with your Homestead environment. As files within these folders are changed, they will be kept in sync between your local machine and the Homestead environment. You may configure as many shared folders as necessary.

folders:
    - map: ~/Code
      to: /home/vagrant/Code

To enable NFS, just add a simple flag to your synced folder configuration.

folders:
    - map: ~/Code
      to: /home/vagrant/Code
      type: "nfs"

You can also pass any options supported by Vagrant synced folders by listing them under the option key.

folders:
    - map: ~/Code
      to: /home/vagrant/Code
      type: "rsync"
      options:
          rsync__args: ["--verbose", "--archive", "--delete", "-zz"]
          rsync__exclude: ["node_modules"]

Configuring Nginx Sites

The sites property allows you to easily map a domain to the folder on your homestead environment. A sample site configuration is included in the Homestead.yaml file.

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public

If you change the sites property after supply the homestead box, you should re-run vagrant reload–provision to update the Nginx configuration on the virtual machine.

The Hosts File

The hosts file will redirect request for your Homestead sites into your Homestead machine. On Mac and Linux file is located at /etc/hosts. On window it is loacted at C:\Windows\System32\drivers\etc\hosts.

192.168.10.10  homestead.app

Make sure the IP address listed is the one set in your Homestead.yaml file.

http://homestead.app

Launching The Vagrant Box

You have edited the Homestead.yaml to your liking, run the vagrant up command from your Homestead directory. It will boot the machine and automatically configure your shared folder and Nginx sites.

If you want to destroy the machine you can use the vagrant destroy –force command.

Per Project Installation

Earlier of installing Homestead globally and sharing the same Homestead box across all of your projects, you may earlier configure a Homestead instance for each project you manage

To install Homestead directly into your project. Require it using composer.

composer require laravel/homestead --dev

When Homestead has been installed, use the make command to generate the vagrantfile and Homestead.yaml file in your project root. The make command will automatically configure the sites and folders directive in the homestead.yaml.

Mac/Linux:

php vendor/bin/homestead make

Windows:

vendor\\bin\\homestead make

Installing MariaDB

If you prefer to use MariaDB instead of mysql. You may add the mariadb option to your homestead.yaml file. This option will remove MYSQL and instal MariaDB.

box: laravel/homestead
ip: "192.168.20.20"
memory: 2048
cpus: 4
provider: virtualbox
mariadb: true

3. Daily Usage.

Accessing Homestead Globally

Sometimes you want to vagrant up your homestead machine from anywhere on your filesystem. You can do this on Mac/Linux systems by adding a bash function to your bash profile. On window, you may accomplish this by adding a “batch” file to your path.

Mac/Linux:

function homestead() {
    ( cd ~/Homestead && vagrant $* )
}

Window:

@echo off

set cwd=%cd%
set homesteadVagrant=C:\Homestead

cd /d %homesteadVagrant% && vagrant %*
cd /d %cwd%

set cwd=
set homesteadVagrant=

Connecting Via SSH

You can SSH into your virtual machine by issuing the vagrant ssh terminal command from your Homestead directory.

Connecting To Databases

A Homestead database is configured for both MySql and Postgres out of the box. Laravel .env file configures the framework to use this database out of the box.

To connect the database, you should connect to 127.0.0.1 and port 33060 MySql or 54320 Postgres. The username and password for both databases is homestead / secret.

Adding Additional Sites

You can run as many Laravel installations as you wish on a single Homestead environment. To add an additional site, simply add the site to your Homestead.yaml file.

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public
    - map: another.app
      to: /home/vagrant/Code/another/public

If Vagrant is not automatically managing your “hosts” file, you may need to add the new site to that file as well

192.168.10.10  homestead.app
192.168.10.10  another.app

Site Types

Homestead supports several types of sites which allow you to easily run projects that are not based on Laravel

sites:
    - map: symfony2.app
      to: /home/vagrant/Code/Symfony/public
      type: symfony2

Configuring Cron Schedules

The schedule:run command will examine the job schedule defined in your App/console/kernel class to determine which jobs should be run. You can set the schedule option to true when you define sites.

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public
       schedule: true

Ports

By default, the following ports are forwaded to your homestead environment.

SSH:2222 → Forwards To 22
HTTP:8000 → Forwards To 80
HTTPS:44300 → Forwards To 443
MySQL:33060 → Forwards To 3306
Postgres:54320 → Forwards To 5432
Mailhog:8025 → Forwards To 8025

Forwarding Additional Ports

If you wish, you may forward additional ports to the Vagrant box, as well as specify their protocol

ports:
    - send: 93000
      to: 9300
    - send: 7777
      to: 777
      protocol: udp

Sharing Your Environment

Sometimes you may wish to share what you’re currently working on with coworkers or a client. Vagrant has a built-in way to support this via vagrant share; however, this will not work if you have multiple sites configured in your Homestead.yaml file.

To solve this problem, Homestead includes its own share command.

share homestead.app

After running the command, you will see an Ngrok screen appear which contains the activity log and the publicly accessible URLs for the shared site.

share homestead.app -region=eu -subdomain=laravel

4. Network Interfaces.

The networks property of the Homestead.yaml configures networks interfaces for your Homestead environment. You may configure as many interfaces as neccessary.

networks:
    - type: "private_network"
      ip: "192.168.10.20"

To enable a bridge interface, configure a bridge setting and change the network type of public network.

networks:
    - type: "public_network"
      ip: "192.168.10.20"
      bridge: "en1: Wi-Fi (AirPort)"

To enable DHCP, just remove the ip option from your configuration.

networks:
    - type: "public_network"
      bridge: "en1: Wi-Fi (AirPort)"

5. Updating Homestead.

You can update Homestead in two simple way. First, you should update the vagrant box using this command.

vagrant box update

If you have installed Homestead via your project’s composer.json file, you should ensure your composer.json file contains “laravel/homestead”: “^4” and update your dependencies.

composer update

6. Old Versions.

You can easily override the version of the box that Homestead uses by adding the following line to your Homestead.yaml file.

version: 0.6.0

An Example:

box: laravel/homestead
version: 0.6.0
ip: "192.168.20.20"
memory: 2048
cpus: 4
provider: virtualbox

The old version will be updated like this:-

Laravel Homestead

7. Provider Specific Settings.

VirtualBox

By default, Homestead configures the natdnshostresolver setting to on. This allows Homestead to use your host operating system’s DNS settings. If you would like to override
this behaviour, add the following lines to your Homestead.yaml file.

provider: virtualbox
natdnshostresolver: off

Laravel Directory Structure


Laravel Directory Structure – Laravel directory structure is used to define where your directory is located.


Laravel Directory Structure.

Let us understand how to use directory structure.

Function:-

There are some followings function to describe directory structure.

  • 1. Introduction.
  • 2. The Root Directory.
  • 3. The App Directory.

1. Introduction.

The default laravel application structure is intended to provide a great starting point for both large and small application. You are free to organize your application however you like. Laravel imposes almost no restrictions on where any given class is located- as long as composer can autoload the class.

Where is the model directory?

When we started with Laravel, many developers is confused by the lack of models directory. however, the lack of such a directory is intentional. We find the word “models” ambiguous since it means many different things to many different people. Some developers refer to an application’s “model” as the totality of all of its business logic, while others refer to “models” as classes that interact with a relational database.

For this reason, we choose to place Eloquent models in the app directory by default and allow the developer to place them somewhere else if they choose.

2. The Root Directory.

Here we are going to show root directory in laravel.

The App Directory

The app directory, as you might expect, contain the core code of your application. We will explore this directory in more details soon. However, almost all of the class in your application will be in this directory.

The Bootstrap Directory.

The bootstrap directory contains file that bootstrap the framework and configure autoloading. This directory also houses a cache directory which contains framework generated files for performance optimization such as the route and services cache files.

The Config Directory.

The config directory, as the name implies, hold all of your application’s configuration file. It is easy to read through all of these files and familiarize yourself with all of the option available to you.

The Database Directory.

The database directory hold your database migration and seeds. If you want, you may also use this directory to hold an SQLite database.

The Public Directory.

The public directory hold the index.php file, which is the entry point for all requests entering your application. This directory also keep your assets such as images, javascript and CSS.

The Resources Directory.

The resources directory hold your views as well as your raw, un-compiled assets such as LESS, SASS or javascript. This directory also keep all of your language files.

The Routes Directory.

The routes directory hold all of the route definations for your application. By default, several route files are included with Laravel: web.php, api.php, console.php and channels.php.

The web.php file hold routes that the RouteServerProvider places in the web middleware group, which provides session states, CSRF protection and cookie encryption. All of your route will be mostly defined in the web.php file.

The api.php file hold routes that the RouteServerProvider places in the api middleware group, which provide rate limiting.

The console.php a file is where you can define all of your closure based console commands. Each closure is bounded to a command instance allowing a simple approach to interacting with each command’s IO method. This file does not define HTTP routes. Its define console based entry points into your application.

The channel.php file is where you can register all of the event broadcasting channnels that your application supports.

The Storage Directory.

The storage directory hold your compiled blade templates, file based sessions, file caches and other file generated by the framework. The directory is segregated into app, framework and logs directories. The app directory is used to store any files generated by your application. The framework directory is used to store framework generated files and caches. Finally, the logs directory hold your application’s log files.

The storage/app/public directory is used to store user generated files, such as profile avatars, that should be publically accessible. You may create the link using php artisan storage:link command.

The Tests Directory.

The tests directory hold your automated tests. An example PHPUnit is provided out of the box.
Each test class should be suffixed with the word test. You may run your tests using the phpunit or php vender/bin/phpunit commands.

The Vendor Directory.

The vender directory hold your composer dependencies.

3. The App Directory.

The majority of your application is keep in the app directory. By default, this directory is namespaced under App and is autoloaded by composer.

The app directory hold variety of additional directories such as console, Http and providers. Think of the console and Http dirctories as providing an API into the core of your application. The console directory hold all of yourArtisan commands, while the http directory hold your controller, middleware and requests.

The Console Directory

The console directory hold all of the custom artisan commands for your application. these command may be generated using the make:command command. This directory also keep your console kernel, which is where your custom artisan command are registered.

The Events Directory

This directory does not exits by default, but will be created for you by the event:generate and make:event Artisan commands. Event may be used to alert other part of your application that a given action has occurred, providing a great deal of flexibility and decoupling.

The Exceptions Directory

The Exceptions directory hold your application’s exception handler and is also a good place to place any exception thrown by your application. If you would like to customize how your exceptions are logged or rendered, you should modify the handler class in this directory.

The Http Directory

The Http directory hold your controllers, middleware and form requests. Almost all of the logic to handle request entering your application will be placed in this directory.

The Jobs Directory

This directory does not exist by default but will be created for you. if you execute the make:job Artisan command. Jobs may be queued by your application or run synchronously within the current request lifecycle.

The Listeners Directory

The directory does not exist by default, but will be created for you. If you execute the event:generate or make:listener Artisan commands. The listeners directory hold the classes that handle your events.

The Mail Directory

This directory does not exist by default, but will be cretaed for you. If you execute the make:mail
Artisan commands. The mail directory hold all of your classes that represent emails sent by your application.

The Notification Directory

This directory does not exist by default but will be created for you. If you execute the make:notification Artisan command. The notification directory hold all of the transactional notification that are sent by your application. Laravel’s notification features abstract sending notifications over a variety of driver such as email, slacks, sms stored in the database.

The Policies Directory

This directory does not exist by default but will be created for you. If you execute the make:policy Artisan command. The policy directory hold the authorization policy classes for your application. policies are used to determine if a user can perform a given action against a resource.

The Providers Directory

The provider directory hold all of the serviceproviders for your application. Service providers bootstrap your application by binding services in the service container, registering events or performing any other task to prepare your application for incoming requests.

In a fresh Laravel application, this directory will already hold several providers. You are free to add your own providers to this directory as needed.

Laravel Configuration Process


Laravel Configuration Process – Here we are going to explain how to configuration laravel.


Laravel Configuration Process.

Let us understand how to configure laravel.

Functions:-

There are some followings process to configure laravel.

  • 1. Introduction.
  • 2. Environment configuration.
  • 3. Accessing configuration values.
  • 4. Configuration caching.
  • 5. Maintenance mode.

1. Introduction.

All of the configuration file for the laravel framework are stored in the config directory. Each option is documented, so feel free to look through the file and get familiar with the options available to you.

2. Environment configuration.

It is many time helpful to have different configuration values based on the enviroment where the application is running. For example, you may wish to use a different cache diver locally than you do on your production server.

Laravel use the DotEnv PHP library. In a fresh Laravel installation, the root directory of your application will contain a .env.example file. If you install Laravel via composer, this file will automatically be renamed to .env. otherwise you should rename the file manually

Retrieving Environment Configuration

all the variables listed in this file will be loaded into the $_ENV PHP super global when your application recieve a request. Yet, you may use the env helper to retrieve values from these variables in your configuration files

'debug' => env('APP_DEBUG', false),

Determining The Current Environment

the current application enviroment is determined via the APP_ENV variable from your .env file.
You may access this value via the enviroment method on the app.

$environment = App::environment();

You may also pass arguments to the enviroment method to check if teh enviroment matches a given value.
the method will return true if the enviroment matches any of the given values:

if (App::environment('local')) 
{
    // The environment is local.
}

if (App::environment('local', 'staging')) 
{
    // The environment is either local OR staging.
}

3. Accessing configuration values.

The configuration values may be accessed using “dot” syntax, which include the name of the file and option you wish to access. A default value may also be specified and will be returned if the configuration option does not exit.

$value = config('app.timezone');

To set configuration value at runtime, pass an array to the config helper.

config(['app.timezone' => 'America/Chicago']);

4. Configuration caching.

To give your application a speed boost, you should cache all of your configuration files into a single file using the config:cache Artisan command. This will combine all of the configuration option for your application into a single file which will be loaded quickly by the framework.

You should typically run the php artisan config:cache command as part of your production deployment routine.

5. Maintenance mode.

When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to “disable” your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application. If the application is in maintenance mode, a MaintenanceModeException will be thrown with a status code of 503.

To enable maintenance mode, simply execute the down Artisan command:

php artisan down

You may also provide message and retry options to the down command.

php artisan down --message="Upgrading Database" --retry=60

To disable maintenance mode, use the up command.

php artisan up

Maintenance Mode Response Template.

The default template for maintenance mode responses is located in resources/views/errors/503.blade.php.
You are free to modify this view as needed for your application.

Maintenance Mode & Queues.

While your application is in maintenance mode, no queuedjobs will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode.

Alternatives To Maintenance Mode.

Since maintenance mode requires your application to have several seconds of downtime, consider alternatives like Envoyer to accomplish zero downtime deployment with Laravel.

Laravel Installation Steps


Laravel Installation Steps – We can simply install laravel using these steps.


Laravel Installation Steps.

Let us understand how to install laravel.

Steps:-

There are some followings Steps to install laravel.

  • 1. Server requirement.
  • 2. Installing laravel.
  • 3. Configuration.
  • 4. Web server configuration.

1. Server requirement.

The laravel farmework has a some system requirements. all of these requirements are satisfied by laravel homestead virtual machine, so it is higly recommended that you use homestead as your local laravel developement requiement.

Still, if you are not using homestead, you will need to make sure your server meet the following requirements:
PHP 5.6.4
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension

2. Installing laravel.

Laravel utilizes Composer to manage its dependencies. So, before using laravel, make sure you have composer installed in your computer.

Via Laravel Installer.

First, download the laravel installer using composer.

composer global require "laravel/installer"

Make sure to put the $HOME/.composer/vender/bin directory in your $PATH so the laravel executable can be located by your system.

Once installed, the laravel new command will be created a fresh laravel installation in your specific directory.

laravel new blog

Via Composer Create-Project.

You may also install laravel by using the composer create project command in your terminal.

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

Local Development Server.

If you have PHP installed separated and you would like to use PHP is built in development server to serve your application, you may use the serve Artisan command. This command will start a development serevr at
http://localhost:8000:

php artisan serve

3. Configuration.

Public directory.

After installing laravel, you should configure your web server’s document/web root to be the public directory. The index.php in this directory serves as the front controller or all HTTP requests entering
your application.

Configuration Files.

All of the configuration files foe the laravel framework are stored in config directory.

Directory Permissions.

After installing laravel, you have to need configure some permission. Directories within the storage and the bootstarp/cache directories should be writable by your web server or laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

Application Key.

The next thing after installing Laravel is set your application key to a random string. If you installed Laravel via composer or the Laravel installer, this key has already been set for you by the php artisan key:generate command.

If the application key is not set, yours users sessions and other encrypted data will be not secure!

Additional Configuration.

laravel needs almost no other configuration out of the box. you are free to get started developing. However you may wish to review the config/app.php file and its documentation

You may also want to configure a few additional components of laravel, such as:
Cache
Database
Session

4. Web server configuration.

Pretty URLs

Apache

laravel includes a public/.htaccess file that is used to provide URL without the index.php front controller in the path. before serving laravel with apache be sure to enable the mod_rewrite module so the .htaccess file will be honored by the server.

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Nginx

If you are using nginx, the following directive in your site configuration will direct all requests to the index.php front controller:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}