Category Archives: Laravel Tutorial

Laravel Encryption


Laravel Encryption – The Laravel Encryption is used to provide a encryption facility to encrypte the data.


Laravel Encryption.

Let us understand how to use laravel Encryption.

Function:-

There are some followings function available in laravel Encryption.

  • 1. Introduction.
  • 2. Configuration.
  • 3. Using The Encrypter.

1. Introduction.

Laravel encrypter use open source implementation protocol to provide AES-256 and AES-128 encryption. You are stronly encouraged to use laravel built in encryption and not attempt to roll your own encryption algorithm. Laravel encrypted value are signed using a message authentication code and value can not be modify once encrypted.

2. Configuration.

Before using laravel encrypter, you must set a key option in your config/app.php configuration file. You should use the php artisan key:generate
command to generate this key since this artisan command will use PHP’s secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.

3. Using The Encrypter.

Encrypting A Value

We can encrypt a value using the encrypt helper. All encrypted value are encrypted using open source implementation and the AES-256-CBC cipher. All encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string

Let’s look at a simple example.

fill([
            'secret' => encrypt($request->secret)
        ])->save();
    }
}

Encrypting Without Serialization

Encrypted values are passed through serialize during encryption which is allows for encryption of object and arrays. Non-PHP client recieving encrypted values will need to unserialize the data. If you want to encrypt and decrypt values without serialization,
you can use the encryptString and decryptString method.

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

$decrypted = Crypt::decryptString($encrypted);

Decrypting A Value

You may decrypt values using the decrypt helper. If the value can not be properly decrypted, such as when the MAC is invalid, an Illuminate/Contracts/Encryption/DecryptException will be thrown.

use Illuminate\Contracts\Encryption\DecryptException;

try {
    $decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
    //
}

Laravel API Authentication


Laravel API Authentication – The Laravel API Authentication typically uses tokens to authenticate user and do not maintain session state between requests.


Laravel API Authentication.

Let us understand how to use laravel API Authentication.

Function:-

There are followings functions available in laravel API Authentication.

  • 1. Introduction.
  • 2. Installation.
  • 3. Configuration.
  • 4. Issuing Access Tokens.
  • 5. Password Grant Tokens.
  • 6. Implicit Grant Tokens.
  • 7. Client Credentials Grant Tokens.
  • 8. Personal Access Tokens.
  • 9. Protecting Routes.
  • 10. Token Scopes.
  • 11. Consuming Your API With JavaScript.
  • 12. Events.
  • 13. Testing.

1. Introduction.

Laravel makes easy to perform authentication via login forms. Api authentication uses token to authenticate and do not maintain session state between request. It makes API authentication a breeze using passport which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.

2. Installation.

Lets start to install passport via composer.

composer require laravel/passport

Then, register the passport service provider in the providers array of your config/app.php file.

Laravel\Passport\PassportServiceProvider::class,

The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after registering the provider.

php artisan migrate

Then, you should run the passport:install command. This command will create encryption key need to generate secure access token.

php artisan passport:install

After running this command add the Laravel/Passport/HasApiTokens trait to your App/User model.

Let’s look at a simple example.


Then, you should call the Passport::routes method within the boot method of your AuthServiceProvider.

Let's look at a simple example.

 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }
}

Finally in your config/auth.php configure file, you should set the driver option of the api authentication guard to passport.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Frontend Quickstart

Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens.

To publish the passport Vue components, use the vendor:publish Artsian command.

php artisan vendor:publish --tag=passport-components

The published components will be placed in your resources/assets/js/components directory.

Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

After registering the components, make sure to run npm run dev to recompile your assets.




Deploying Passport

When deploying passport to your production server for the first time, you will likely need to run the passport:keys command.

php artisan passport:keys

3. Configuration.

Token Lifetimes

If you want to configure a shorter token lifetime, you can use the tokensExpireIn and refreshTokensExpireIn methods.

Let's look at a simple example.

use Carbon\Carbon;

public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensExpireIn(Carbon::now()->addDays(15));

    Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}

4. Issuing Access Tokens.

When we are using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.

Managing Clients

When developer building application that needs to interact with your application API will need to register their application with yours by creating a client. The consist of providing the name of their application and a URL that can redirect to after users approve their request for authorization.

The passport:client command

To create a client is using the passport:client Artsian command. This command may be used to create your own clients for testing your oAuth2 functionality. When you run the client command Passport will prompt you for more information about your client and will provide you with a client ID and secret.

php artisan passport:client

JSON API

Passport provides a JSON API that you can use to create clients.

GET /oauth/clients

This route return all of the clients for the authenticated user.

axios.get('/oauth/clients')
    .then(response => {
        console.log(response.data);
    });

POST /oauth/clients

This route is used to create new clients. It requires two pieces of data, the client name and redirect URL.

const data = {
    name: 'Client Name',
    redirect: 'http://example.com/callback'
};

axios.post('/oauth/clients', data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // List errors on response...
    });

PUT /oauth/clients/{client-id}

This route is used to update clients.

const data = {
    name: 'New Client Name',
    redirect: 'http://example.com/callback'
};

axios.put('/oauth/clients/' + clientId, data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // List errors on response...
    });

DELETE /oauth/clients/{client-id}

This route is used to delete clients.

axios.delete('/oauth/clients/' + clientId)
    .then(response => {
        //
    });

Requesting Tokens

Redirecting For Authorization

Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application.

Route::get('/redirect', function () {
    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://example.com/callback',
        'response_type' => 'code',
        'scope' => '',
    ]);

    return redirect('http://your-app.com/oauth/authorize?'.$query);
});

Laravel Authentication


Laravel Authentication – The Laravel Authentication facility is made up of “Guards” and “Providers”. Guard define how user are authenticate for each request and provider define how user retrieve from your persistance storage.


Laravel Authentication.

Let us understand how to use laravel Authentication.

Function:-

There are some followings function available in laravel Authentication.

  • 1. Introduction.
  • 2. Authentication Quickstart.
  • 3. Manually Authenticating Users.
  • 4. HTTP Basic Authentication.
  • 5. Adding Custom Guards.
  • 6. Adding Custom User Providers.
  • 7. Events.

1. Introduction.

Laravel’s make implementing authentication very simple. Almost every thing is configure for you out of box. This file is located at config/auth.php which hold several well document option for tweaking the behavior of the authentication services.

Larvel authentication is using two way Guards and Providers. guards define user authentocation and providers define user retrieve from the storage.

Database Considerations

Laravel includes an App/User in your app directory. This model can be used with the default Eloquent authentication driver. If your application is not using eloquent, you can use the database authentication driver which uses the laravel query builder.

2. Authentication Quickstart.

Laravel ships with several pre-built authentication controller, which are located in the App/Http/controllers/Auth namespace. The RegisterController handles new user registration, the LoginController handles authentication, the ForgotPasswordController handles e-mailing links for resetting passwords and the ResetPasswordController contain the logic of reset password.

Routing

Laravel provides a way to scaffold all of the routes and views you need for authentication using a command.

php artisan make:auth

This Artsian command should be used on fresh application and will install a layout view, login view and registration views, as well as routes for all authentication end points.

Views

The php artsian make:auth command will create all of the views you need for authentication and place them at resources/views/auth directory.

All of these views use the bootstrap CSS framework but you are free to customize them.

Authenticating

By using authenticate controller we can setup route and views. If you want to register new user in your application, you can simply access your application in a browser with authenticate controller.

Path customization

When user successfully authenticated, it will be redirect to the /home page. We can customize the post authentication redirect location by defining a redirectTo property on the login, register andrestPassword Controller.

protected $redirectTo = '/';
protected function redirectTo()
{
    return '/path';
}

Username Customization

Laravel use by default email field for authentication. If you want to customize this,
you can define a username method on your LoginController.

public function username()
{
    return 'username';
}

Guard Customization

You can also customize the Guard which is used to authenticate and register users. Define a guard on your Login, Register and resetPassword Controller and return Guard instance.

Let’s look at a simple example.

use Illuminate\Support\Facades\Auth;

protected function guard()
{
    return Auth::guard('guard-name');
}

Retrieving The Authenticated User

You can access the authenticated user via Auth facade.

use Illuminate\Support\Facades\Auth;

$user = Auth::user();

$id = Auth::id();

Once a user is authenticated, you can access the authenticated use via an Illuminate/Http/Request instance.

Let’s look at a simple example.

user() returns an instance of the authenticated user...
    }
}

Determining If The Current User Is Authenticated

If the user is already logged in your application, you can use the check method on the Auth facade and return true if the user is authenticated.

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

Protecting Routes

Laravel ship with an auth middleware, which is defined at Illuminate/Auth/Middleware/Authenticate. since this middleware already registered in your HTTP Kernel.

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth');

Specifying A Guard

The guard specify should correspond to one of the key in the guard array of your auth.php configuration file.

public function __construct()
{
    $this->middleware('auth:api');
}

3. Manually Authenticating Users.

You will access laravel authentication service via the Auth facade. So you will make sure to import the Auth facade at the top of the class and then check out the attempt method.

Let’s look at a simple example.

 $email, 'password' => $password])) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

The attempt method will true if authentication was sucessfull otherwise it will return false.

Specifying Additional Conditions

You can also add extra condition to the authentication query in addition to the user’s email and password.

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) 
{
    //.......
}

Accessing Specific Guard Instances

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file.

if (Auth::guard('admin')->attempt($credentials)) {
    //.....
}

Logging Out

For logout you can use logout method on the Auth facade

Auth::logout();

Remembering Users

If you want to provide remeber me functionality in your application, you can pass a boolean value as the second argument to the attempt method which will keep the authentication indefinitely or untill they manually logout.

if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
    // The user is being remembered...
}
if (Auth::viaRemember()) 
{
    //
}

Other Authentication Methods

Authenticate A User Instance

If you need to log an existing user instance into your application, you can call the login method with the user instance.

Auth::login($user);

// Login and "remember" the given user...
Auth::login($user, true);

You can specify the guard instance you want to use.

Auth::guard('admin')->login($user);

Authenticate A User By ID

If the user login in your application by their ID, you can use the loginUsingId method.

Auth::loginUsingId(1);

// Login and "remember" the given user...
Auth::loginUsingId(1, true);

Authenticate A User Once

If the user want to login in the application for a single request, you can use once
method.

if (Auth::once($credentials)) {
    //
}

4. HTTP Basic Authentication.

It provides a quick way to authenticate users of your application without setting up a dedication login page. Attach the auth.basic middleware to the controller.

Route::get('profile', function () {
    // Only authenticated users may enter...
})->middleware('auth.basic');

A Note On FastCGI

If we are using PHP FastCGI, HTTP basic authentication can not work correctly out of the box.Then following code should be added in .htaccess file.

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Stateless HTTP Basic Authentication

You can also use HTTP basic authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication

Let’s look at a simple example.


Then register the route middleware and attach it to a route.

Route::get('api/user', function () {
    // Only authenticated users may enter...
})->middleware('auth.basic.once');

5. Adding Custom Guards.

We can define authentication guards using the extend method on the auth
facade. We should place this call to provider within a service provider.

Let's look at a simple example.

registerPolicies();

        Auth::extend('jwt', function ($app, $name, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\Guard...

            return new JwtGuard(Auth::createUserProvider($config['provider']));
        });
    }
}

The callback passed to the extend method should return an implementation of Illuminate/Contracts/Auth/Guards. If you custom guard has been defined, you can use this guard in the guards configuration in your auth.php file.

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

6. Adding Custom User Providers.

If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider.

Let's look at a simple example.

registerPolicies();

        Auth::provider('riak', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new RiakUserProvider($app->make('riak.connection'));
        });
    }
}

After that registered the provider using the provider method, you can switch to the new user provider in your auth.php configuration file.

'providers' => [
    'users' => [
        'driver' => 'riak',
    ],
],

You can use this provider in your guards configuration.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
],

The User Provider Contract

The Illuminate/Contracts/Auth/UserProvider implementation are only responsible for fetching a Illuminate/Contracts/Auth/Authenticable implementation out of a persistant storage system, Such as MySql, Riak etc.

Let's look at a simple example.


The retrieveById function is used to recieve a key representing the user.

The retrieveByToken function is used to retrieve a user by their unique $identifier and remeber me $token, stored in field remeber_token.

The updateRememberToken function is used to update the user field.

The retrieveByCredentials method is used to recieve the array of credential passed to the Auth::attempt method when attempting to sign into an application.

The validateCredentials is used to compare the given user with the credentials to authenticate the user.

The Authenticatable Contract

We have investigate each of the method on the userProvider. Remeber provider should return implementation of this interface from the retrieveById and retrieveByCredentials method.

Let's look at a simple example.


7. Events.

Laravel Raise a vareity of events during the authentication process.

Let's look at a simple example.

protected $listen = [
    'Illuminate\Auth\Events\Registered' => [
        'App\Listeners\LogRegisteredUser',
    ],

    'Illuminate\Auth\Events\Attempting' => [
        'App\Listeners\LogAuthenticationAttempt',
    ],

    'Illuminate\Auth\Events\Authenticated' => [
        'App\Listeners\LogAuthenticated',
    ],

    'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

    'Illuminate\Auth\Events\Failed' => [
        'App\Listeners\LogFailedLogin',
    ],

    'Illuminate\Auth\Events\Logout' => [
        'App\Listeners\LogSuccessfulLogout',
    ],

    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];

Laravel Compiling Assets


Laravel Compiling Assets – The Laravel Compiling Assets provides a fluent API for defining webpack make steps for your application using several CSS and javaScript pre-processor.


Laravel Compiling Assets.

Let us understand how to use laravel Compiling Assets.

Function:-

There are following functions available in laravel Compiling Assets.

  • 1. Introduction.
  • 2. Installation & Setup.
  • 3. Running Mix.
  • 4. Working With Stylesheets.
  • 5. Working With JavaScript.
  • 6. Copying Files & Directories.
  • 7. Versioning / Cache Busting.
  • 8. Browsersync Reloading.
  • 9. Environment Variables.
  • 10. Notifications.

1. Introduction.

It provides a fluent API for defining webpack make steps for your laravel application using several CSS and javaScript pre-processor. By using simple method chaining, You can define your assets with pipeline like this:-

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

2. Installation & Setup.

Installing Node

Before triggering Mix, you have to ensure that Node.js and NPM are installed on your machine.

node -v
npm -v

If you are not using vagrant, then you can easily install the latest version of node and NPM.

Laravel Mix

The only remaining step is to install laravel mix. Within a fresh installation of laravel, you will find a package.json file in the root of your directory structure. You can istall the dependencies it references by running this code.

npm install

If you are running your VM on a window host system. You have to run the npm install command with the –no-bin-links switch enabled.

npm install --no-bin-links

3. Running Mix.

Mix is a configuration layer on top of Webpack, so to run your Mix tasks you only need to execute one of the NPM scripts that is included with the laravel package.json file.

npm run dev
npm run production

Watching Assets For Changes

To watching all relevent file for changes, we use npm run watch command will continue running in your terminal.

npm run watch

You can find that in environment Webpacks is not updating when your file changes.

npm run watch-poll

4. Working With Stylesheets.

The webpack.mix.js file is your entry point for all asset compilation. Think of it as a light configuration wrapper around Webpack. Mix tasks can be chained together to define exactly how your assets should be compiled.

Less

We use less method to compile LESS into CSS.

mix.less('resources/assets/less/app.less', 'public/css');

Multiple calls to the less method can be used to compile multiple files.

mix.less('resources/assets/less/app.less', 'public/css')
   .less('resources/assets/less/admin.less', 'public/css');

You want to customize the file name of CSS, You may pass the full path as a second argument.

mix.less('resources/assets/less/app.less', 'public/stylesheets/styles.css');

Sass

The Sass method allows you to compile Sass into Css.

mix.sass('resources/assets/sass/app.scss', 'public/css');

You can also compile multiple sass file like less method.

mix.sass('resources/assets/sass/app.sass', 'public/css')
   .sass('resources/assets/sass/admin.sass', 'public/css/admin');

Additional Node-sass plug-in option may be provided as the third argument.

mix.sass('resources/assets/sass/app.sass', 'public/css', {
    precision: 5
});

Stylus

It is also similar to less and sass. It allows to compile stylus into css.

mix.stylus('resources/assets/stylus/app.styl', 'public/css');

You can also install additional stylus plug-in, such as Rupture

mix.stylus('resources/assets/stylus/app.styl', 'public/css', {
    use: [
        require('rupture')()
    ]
});

PostCSS

It is a powerful tool for transforming your Css, is included with laravel Mix out of box. Install the desired plug-in through NPM and then reference it in your webpack.mix.js
file.

mix.sass('resources/assets/sass/app.scss', 'public/css')
   .options({
        postCss: [
            require('postcss-css-variables')()
        ]
   });

Plain CSS

You want to concatenate some plain CSS stylesheets into a single file, you can use the style method.

mix.styles([
    'public/css/vendor/normalize.css',
    'public/css/vendor/videojs.css'
], 'public/css/all.css');

URL Processing

You may use URL processing for CSS compilation, Webpack will rewrite and optimize any url() call within your stylesheets.

.example {
    background: url('../images/example.png');
}

Source Maps

Source map can be activated by calling the mix.sourceMaps() method in your webpack.mix.js file.

mix.js('resources/assets/js/app.js', 'public/js')
   .sourceMaps();

5. Working With JavaScript.

Mix provides several features to help you work with your JavaScript files, such as compiling ECMAScript 2015, module bundling, minification, and simply concatenating plain JavaScript files. Even better, this all works seamlessly, without requiring an ounce of custom configuration

mix.js('resources/assets/js/app.js', 'public/js');

Using single line of code you can take advantage of:-

ES2015 syntax.
Modules
Compilation of .Vue files.
Minification for production environments.

Vendor Extraction

The vendor library is that it take long term chaining. Like a single update to your application code will force the browser to re-download all your vendor library.

mix.js('resources/assets/js/app.js', 'public/js')
   .extract(['vue'])

The extract methods accept array of all library or modules that you want to extract into a vendor.js

public/js/manifest.js: The webpack manifest runtime
public/js/vendor.js: Your vendor libraries.
public/js/app.js: Your application code.

To avoid javascript code, to load these file in proper way.




React

Mix can automatically install the Babel plug-ins for React support. It replace your mix.js() call with mix.react().

mix.react('resources/assets/js/app.jsx', 'public/js');

Vanilla JS

It is similar to combining stylesheets with mix.style(), you can also combine and minify any number of javascript files with script() methods.

mix.scripts([
    'public/js/admin.js',
    'public/js/dashboard.js'
], 'public/js/all.js');

Custom Webpack Configuration

The webpack.config.js method is use to get file to you up and running as quickly as possible. You may need to manually modify this file.

Merging Custom Configuration

Mix provide a useful webpackconfig method which allows you to merge any short webpack configuration override. The webpackconfig method accepts an object.

mix.webpackConfig({
    resolve: {
        modules: [
            path.resolve(__dirname, 'vendor/laravel/spark/resources/assets/js')
        ]
    }
});

Custom Configuration Files

If you want completely customize your webpack configuration, copy the node_modules/laravel-mix/setupwebpack.config.js file to your project directory. Then point all of the –config references in your package.json file to the newly copied configuration file.

6. Copying Files & Directories.

The copy method can be used to copy files and directories to new locations. This is useful when a particular asset within your node_modules directory need to be relocated to your public folder.

mix.copy('node_modules/foo/bar.css', 'public/css/bar.css');

When copying a directory, the copy method will flatten the directory structure.

mix.copyDirectory('assets/img', 'public/img');

7. Versioning / Cache Busting.

Many developer suffix their compiled assets with a timestamp or unique token to force browser to load the fresh assets instead of serving stale copies of the code. Mix can handle this to using version method.

This method is automatically append a unique hash to the file name of all compile file.

mix.js('resources/assets/js/app.js', 'public/js')
   .version();

After generating the version file, you want know the exact file name. Then you should use Laravel’s global mix function.


Because versonied file are usually unnecessary in development, you may like to instruct the versioning process to only run during npm run production.

Let’s look at a simple example.

mix.js('resources/assets/js/app.js', 'public/js');

if (mix.config.inProduction) {
    mix.version();
}

8. Browsersync Reloading.

BrowserSync can automatically monitor your file for changes and inject your changes in browser without need a manuall refresh. You can enable support by calling the mix.browserSync() method.

Let’s look at a simple example.

mix.browserSync('my-domain.dev');

mix.browserSync({
    proxy: 'my-domain.dev'
});

9. Environment Variables.

You may inject enviromental variable in Mix by prefixing a key in you .env file with MIX_.

MIX_SENTRY_DSN_PUBLIC=http://example.com

After the variable has been defined in your .env file, you can access via the process.env object.

process.env.MIX_SENTRY_DSN_PUBLIC

10. Notifications.

When available, Mix will automatically display OS notifications for each bundle. This will give you instant feedback, as to whether the compilation was successful or not. However, there may be instances when you’d prefer to disable these notifications

mix.disableNotifications();

Laravel JavaScript & CSS Scaffolding


Laravel JavaScript & CSS Scaffolding – The Laravel JavaScript & CSS Scaffolding is provides a basic starting point using Bootstrap and Vue that will be helpful for many application.


Laravel JavaScript & CSS Scaffolding.

Let us understand how to use laravel JavaScript & CSS Scaffolding.

Function:-

There are some followings function available in laravel JavaScript & CSS Scaffolding.

  • 1. Introduction.
  • 2. Writing CSS.
  • 3. Writing JavaScript.

1. Introduction.

As a Laravel does not control which javascript or css pre-processor you use. It does provide a basic starting point. By default Laravel use NPM to install both of these frontend packages.

CSS

Laravel Mix provide a clean, expressive API over compiling SASS or less, which are extension or plain CSS that add varialbles, mixins, and other powerful features that make working with CSS much more enjoyable.

JavaScript

Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don’t have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the Vue library.

2. Writing CSS.

Laravel package.json file includes the bootstrap-sass package to help you get started prototyping your application’s frontend using Bootstrap. However, feel free to add or remove packages from the package.json file as needed for your own application

npm install

Once the dependencies have been installed using npm install , you can compile your SASS files to plain CSS using Laravel Mix.

npm run dev

The default webpack.mix.js included with laravel will compile the resources/assets/scss/ SASS file.

3. Writing JavaScript.

All of the javascript dependencies required by your application can be found in the package.json file in the project root directory. The file is similar to the composer.json file except it specifies JavaScript dependencies instead of PHP dependencies.

npm install

Once the packages are installed, you can use the npm run dev command to compile your assets.

npm run dev

The app.js file you can register you Vue component in laravel.

Writing Vue Components

Fresh Laravel application contain Example.vue. Vue component located in the resources/assets/js/components directory. The Example.vue file is an example of a single file Vue component which defines its JavaScript and HTML template in the same file.

Vue.component('example', require('./components/Example.vue'));

To use the component in your application, you can simply drop it into one of your html templates.

@extends('layouts.app')

@section('content')
    
@endsection

Laravel Localization


Laravel Localization – The Laravel Localization is used to support different language to be used in application. You should create a separete directory for each supported language.


Laravel Localization.

Let us understand how to use laravel Localization.

Function:-

There are some followings function available in laravel Localization.

  • 1. Introduction.
  • 2. Defining Translation Strings.
  • 3. Retrieving Translation Strings.
  • 4. Overriding Package Language Files.

1. Introduction.

Laravel localization provide a simple way to access string in multiple languages and allowing you to easily support multiple languages within your application. All string are stored in the file within the resource/lang directory

Configuring The Locale

The default language for your application is stored in the config/app.php configuration file. You can modify this value to suit the needs of your application. You can also change the active language at run time using the setLocale method.

Route::get('welcome/{locale}', function ($locale) {
    App::setLocale($locale);

    //
});

You can also configure a fallback language, the fallback language is also configure in the config/app.php configuration file.

'fallback_locale' => 'en',

Determining The Current Locale

You can use the getLocale and isLocale method on the app facade and also use for check the current locale and given value.

$locale = App::getLocale();

if (App::isLocale('en')) {
    //
}

2. Defining Translation Strings.

Using Short Keys

Translation string are stored in resource/language directory. this directory there should be a subdirectory for each language.

/resources
    /lang
        /en
            messages.php
        /hi
            messages.php

All language file simply return an array of strings.

 'Welcome To Tutorialsplane.com'
];

3. Retrieving Translation Strings.

You can retrieve lines from using _ helper function. The _ method accepts the file and key of the translation string as its first argument.

echo __('messages.welcome');

echo __('I love programming.');

If you are using blade templates. Then you may use {{ }} syntax.

{{ __('messages.welcome') }}

@lang('messages.welcome')

Replacing Parameters In Translation Strings

If you want, you can define place-holder in your translation string. All place-holder are set with :.

'welcome' => 'Welcome, :name',

To replace the place-holders, you may pass the second argument.

echo __('messages.welcome', ['name' => 'Tutorialsplane']);

If the place-holders name contains all capital letter then a value of place-holders is also print capitalized. If the first letter is capitalized then output is same as it is.

'welcome' => 'Welcome, :NAME', // Welcome, TUTORIALSPLANE
'goodbye' => 'Goodbye, :Name', // Goodbye, Tutorialsplane

Pluralization

Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization.

'apples' => 'There is one apple|There are many apples',

You may even create more complex pluralization rules.

'apples' => '{0} There are none|[1,19] There are some|[20,*] There are many',

You can use trans_choice function to retrieve the line for a given count.

echo trans_choice('messages.apples', 10);

4. Overriding Package Language Files.

Some packages may override with their own language file. Earlier of changing of packages core file to adjust these line. You can override them by placing file in the resources/lang/vender/{package}/{locale} directory.

If you need to override the English translation strings in message.php. You should place a language file at resources/lang/vender/hearthfire/en/message.php. you can only define the translation string which is you want.

Full Example of Localization:-

First we have to create three different folder in resources/lang directory. Like save english file at resources/lang/en/lang.php and put the code like this:-

 'Welcome To Tutorialsplane.'
   ];
?>

save french file at resources/lang/fe/lang.php directory.

 'Bienvenue à Tutorialsplane.'
   ];
?>

save german file at resources/lang/ge/lang.php directory.

 'Willkommen bei Tutorialsplane.' 
   ];
?>
Laravel Localization

Then create a controller called LocalizationController through Artsian command.

php artisan make:controller LocalizationController --plain
Laravel Localization

Controller Parts:-

Let’s look at a simple example.

setLocale($locale);
      echo trans('lang.msg');
   }
}

Routes Parts:-

Route::get('localization/{locale}','LocalizationController@index');

Path and Output

http://localhost:/path/localization/en

Laravel Localization

http://localhost:/path/localization/fe

Laravel Localization

http://localhost:/path/localization/ge

Laravel Localization

Laravel Blade Templates


Laravel Blade Templates – The Laravel Blade Templates is used to add essentially zero overhead to your application. Blade view files use the .blade.php file extension and stored in resources/views directory.


Laravel Blade Templates.

Let us understand how to use laravel Blade Templates.

Function:-

There are some followings function available in laravel Blade Templates.

  • 1. Introduction.
  • 2. Template Inheritance.
  • 3. Components & Slots.
  • 4. Displaying Data.
  • 5. Control Structures.
  • 6. Including Sub-Views.
  • 7. Stacks.
  • 8. Service Injection.
  • 9. Extending Blade.

1. Introduction.

It is a powerful templating engine which is provided with Laravel. Blade template engine does not restrict you from using plain php code in your views but the file will be must save in .blade.php extension. and stored in resource/views directory.

2. Template Inheritance.

Defining A Layout

Lets take a look i am going to define a layout. It is convenient to define this layout as a single blade view.

Let’s look at a simple example.

    
        
    
    
        @section('sidebar')
            This is the master sidebar.
        @show

        
@yield('content')

As you can see, we use two directive @section and @yield. The @section directive define a section of content. While the @yield is used to display the content of given section.

Extending A Layout

When we use child view, use the blade @extends directive which specify the layout the child view should inherit

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar')
    @parent

    

This is appended to the master sidebar.

@endsection @section('content')

This is my body content.

@endsection

Route Path:-

Route::get('blade', function () {
    return view('child');
});

3. Components & Slots.

Components and slots provide similar benefits to section and layouts.

{{ $slot }}

The {{ $slot }} variable will contain the content we want to inject into the component.

@component('alert')
    Whoops! Something went wrong!
@endcomponent

Sometimes it is helpfull to define multiple slots for a component.

{{ $title }}
{{ $slot }}

We may inject content into the named slot using the @slot directive.

@component('alert')
    @slot('title')
        Forbidden
    @endslot

    You are not allowed to access this resource!
@endcomponent

Passing Additional Data To Components

Sometimes you have to need to pass additional data to a component. You can also pass an array of data as the second argument to the @component directive.

@component('alert', ['foo' => 'bar'])
    ...
@endcomponent

4. Displaying Data.

You can display data passed to your blade views by taking the variable in curly braces.

Route path:-

Route::get('greeting', function () {
    return view('welcome', ['name' => 'Sonu']);
});

View part:-

Hello, {{ $name }}.

Displaying Unescaped Data

By default, this {{ }} statement are automatically sent through php function to prevent XSS attacks. If you do not want to escaped your data you can use like this:-

Hello, {!! $name !!}

Blade & JavaScript Frameworks

It also uses the curly braces to indicate the given expression should be displayed in a browser. You can also use the @ symbol to inform the Blade rendering engine an expression should remain untouched.

Laravel

Hello, @{{ name }}

The @ symbol will be removed by blade.

The @verbatim Directive

If javascript variable are displaying in a large portion of your template. You can take the HTML in the @verbatim directive.

@verbatim
    
Hello, {{ name }}.
@endverbatim

5. Control Structures.

Blade provides shortcuts for common PHP control structures, like conditional statement and loops.

If Statement

You can construct if statements using the @if, @elseif, @else and @endif directive.

Let’s look at a simple example.

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

Blade also provide @unless directive.

@unless (Auth::check())
    You are not signed in.
@endunless

The @isset and @empty directive is used to shortcuts for their PHP function.

@isset($records)
    // $records is defined and is not null...
@endisset

@empty($records)
    // $records is "empty"...
@endempty

Loops

Blade also provides simple directive for working with PHP loop structure in conditional statements.

Let’s look at a simple example.

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    

This is user {{ $user->id }}

@endforeach @forelse ($users as $user)
  • {{ $user->name }}
  • @empty

    No users

    @endforelse @while (true)

    I'm looping forever.

    @endwhile

    When using loops you can also end the loop or skip the current iteration

    Let’s look at a simple example.

    @foreach ($users as $user)
        @if ($user->type == 1)
            @continue
        @endif
    
        
  • {{ $user->name }}
  • @if ($user->number == 5) @break @endif @endforeach

    You can also include the condition with the directive declaration in one line.

    @foreach ($users as $user)
        @continue($user->type == 1)
    
        
  • {{ $user->name }}
  • @break($user->number == 5) @endforeach

    The Loop Variable

    A $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop

    Let’s look at a simple example.

    @foreach ($users as $user)
        @if ($loop->first)
            This is the first iteration.
        @endif
    
        @if ($loop->last)
            This is the last iteration.
        @endif
    
        

    This is user {{ $user->id }}

    @endforeach

    If you are in nested loop then you can access the parent loops.

    @foreach ($users as $user)
        @foreach ($user->posts as $post)
            @if ($loop->parent->first)
                This is first iteration of the parent loop.
            @endif
        @endforeach
    @endforeach
    

    The $loop variable also contains a variety of other properties.

    Comments

    You can also pass the comment in view part like this:-

    {{-- This comment will not be present in the rendered HTML --}}
    

    6. Including Sub-Views.

    Blade’s @include directive allows you to include a blade view from within another view.

    @include('shared.errors')

    By using include method we will inherit all data available in the parent view.

     @include('view.name', ['some' => 'data'])  
    

    If you want to include a include a view that may or may not be present, then you should use the @includeif directive.

    @includeIf('view.name', ['some' => 'data']) 
    

    7. Stacks.

    Its allows you to push to named stacks which can be rendered somewhere else in another view.

    @push('scripts')
        
    @endpush 
    

    You can push to a stack as more time as needed.

        
    
        @stack('scripts')
    
    

    8. Service Injection.

    The @inject directive can be used to access a service from the laravel Service Container. The first argument passed to @inject is name of the variable and second argument is class or interface name of service which is you want to resolve.

    @inject('metrics', 'App\Services\MetricsService')
    
    
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.

    9. Extending Blade.

    Blade allow you to define your own custom directive by using directive method.

    Let’s look at a simple example.

    format('m/d/Y H:i'); ?>";
            });
        }
        public function register()
        {
            //
        }
    }
    

    Laravel Errors & Logging


    Laravel Errors & Logging – The Laravel Errors & Logging both are different things. Errors and exception handling is already configured for you when you started new project. Logging is important mechanism which can log errors that are generated.


    Laravel Errors & Logging.

    Let us understand how to use laravel Errors & Logging.

    Function:-

    There are some followings function available in laravel Errors & Logging.

    • 1. Introduction.
    • 2. Configuration.
    • 3. The Exception Handler.
    • 4. HTTP Exceptions.
    • 5. Logging.

    1. Introduction.

    Errors.

    When we install a new project. It will be already configured for you. We need to see errors for debugging purpose in a local enviroment. We need to hide these errors from users. The variable APP_DEBUG are achieved to set in environment file.

    Logging.

    It is an important mechanism that are generated log errors by system. Its support different logging mode like single, daily, syslog and errorlog mode. You can set mode in config/app.php file.

    You can generated the logging in storage/logs/laravel.log file.

    'log' => 'daily'
    

    2. Configuration.

    Error Detail

    The debug option detemine how much information about an error is actually display to the users. The debug option is placed in config/app.php. By default, the value of APP_DEBUG id stored in .env file.

    In local environment the APP_DEBUG value should be true but in production we need to be set to false to hide errors.

    Log Storage

    You want to modify then you should go in log option in your config/app.php configuration file.

    Maximum Daily Log Files

    If you are using daily log mode. By default Laravel will only return only five days of log files. If you want to adjust the retained file you may add a log_max_files configure value in your app configure file.

    'log_max_files' => 30
    

    Log Severity Levels

    When using monolog, the message has different level of severity. Laravel writes all log level to storage by default. In production environment, you may wish to configure minimum severity should be logged by adding the log_level option to your app.php configuration file.

    'log_level' => env('APP_LOG_LEVEL', 'error'),
    

    Custom Monolog Configuration

    If you want to take complete controll over how monolog is configured for your application. You can use the application ConfigMonologUsing.

    Let’s look at a simple example.

    $app->configureMonologUsing(function ($monolog) {
        $monolog->pushHandler(...);
    });
    
    return $app;
    

    3. The Exception Handler.

    The exception handler contain two method Repot and Render.

    The Report Method

    It is used to log exception and send them to Bugsnag and Sentry. This method simply pass the exception to the base class where the exception is logged.

    Let’s look at a simple example.

    public function report(Exception $exception)
    {
        if ($exception instanceof CustomException) {
            //
        }
    
        return parent::report($exception);
    }
    

    Ignoring Exceptions By Type

    The $dontReport property of exception handler contains an array of exception types that will not be logged.

    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Validation\ValidationException::class,
    ];
    

    The Render Method

    This method is responsible for converting a given exception into an HTTP response that should be sent back to the browser.

    Let’s look at a simple example.

    public function render($request, Exception $exception)
    {
        if ($exception instanceof CustomException) {
            return response()->view('errors.custom', [], 500);
        }
    
        return parent::render($request, $exception);
    }
    

    4. HTTP Exceptions..

    Exception describe HTTP error code from the server.

    abort(404);
    

    The abort helper will immediately raise an exception which will be rendered by the exception handler.

    abort(403, 'Unauthorized action.');
    

    Custom HTTP Error Pages

    If you want to customize an error page for 404 HTTP status code, create resources/views/errors/404.blade.php.

    {{ $exception->getMessage() }}

    5. Logging.

    Laravel provides a simple abstraction layer on top of the powerful Monolog library.

    Let's look at a simple example.

     User::findOrFail($id)]);
        }
    }
    

    The logger defined eight level in RFC 5424.

    Log::emergency($message);
    Log::alert($message);
    Log::critical($message);
    Log::error($message);
    Log::warning($message);
    Log::notice($message);
    Log::info($message);
    Log::debug($message);
    

    Contextual Information

    Contexual data can also be passed to the log method. It will be formatted and display with log message.

    Log::info('User failed to login.', ['id' => $user->id]);
    

    Accessing The Underlying Monolog Instance

    Monolog has a variety of additional handlers you may use for logging.

    $monolog = Log::getMonolog();
    

    Laravel Validation


    Laravel Validation – The Laravel Validation is used to validate the incoming data. Laravel always check the error in the session data and automatically bind them to the view if they are available.


    Laravel Validation.

    Let us understand how to use laravel Validation.

    Function:-

    There are some followings function available in laravel Validation.

    • 1. Introduction.
    • 2. Validation Quickstart.
    • 3. Form Request Validation.
    • 4. Manually Creating Validators.
    • 5. Working With Error Messages.
    • 6. Available Validation Rules.
    • 7. Conditionally Adding Rules.
    • 8. Validating Arrays.
    • 9. Custom Validation Rules.

    1. Introduction.

    Laravel provide several way to validate your incoming data. Laravel base conmtroller class uses a ValidatesRequests which provide a convenient method to validate incoming HTTP request with powerfull validation rules.

    2. Validation Quickstart.

    To learn about Laravel’s powerful validation feature. Here i am going to explain full example of validate a form and displaying the error message to the user.

    Defining The Routes

    Here we have to defined following routes in our routes/web.php file.

    Route::get('create', 'PostController@create');
    
    Route::post('post', 'PostController@store');
    

    get method is for displaying a form for the user and post method is used to store the data in the database.

    Creating The Controller

    Lets see the simple controller that handle these routes.

    Let’s look at a simple example.

    
    

    Writing The Validation Logic

    Here i am going to explain how to validate input field. We may use validate method to set the validation rules. If the validation rules pass your code will be executed normally.If validation fails the error response will be sent bank to the user.

    To get better understanding of the validate method.

    Let's look at a simple example.

    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);
    }
    

    Stopping On First Validation Failure

    Sometimes you want to stop running validation rules after the first valiadtion failure. That time we are use bail rule to the attribute.

    $this->validate($request, [
        'title' => 'bail|required|unique:posts|max:255',
        'body' => 'required',
    ]);
    

    A Note On Nested Attributes

    If HTTP request has nested parameter. You may specify them in your validation rules using dot syntax.

    $this->validate($request, [
        'title' => 'required|unique:posts|max:255',
        'author.name' => 'required',
        'author.description' => 'required',
    ]);
    

    Displaying The Validation Errors

    Your incoming request do not pass the validation rules. Laravel will automatically redirect the user back to the previous location. The user will be redirected to our controller when validation fails and allowing us to display the error message in the views.

    @if (count($errors) > 0)
            
      @foreach ($errors->all() as $error)
    • {{ $error }}
    • @endforeach
    @endif

    A Note On Optional Fields

    Laravel include the TrimStrings and ConvertEmptyStringToNull middleware in your application. You will need to mark your optional request field as null and do not want the validator to consider null value as invalid.

    $this->validate($request, [
        'title' => 'required|unique:posts|max:250',
        'body' => 'required',
        'publish_at' => 'nullable|date',
    ]);
    

    Customizing The Flashed Error Format

    You want to customize the format of the validation errors that are flashed to the session. When validation fails overRide the formatValidationErrors on your base controller. Most important is don't forget to import Illuminate\Contracts\Validation\Validator class at the top of your controller file.

    Let's look at a simple example.

    errors()->all();
        }
    }
    

    AJAX Requests & Validation

    We used AJAX Request & Validation for traditional form to send data to the application. When using the validate method during an AJAX request. Laravel will not generate a redirect response. Its generates a JSON response.

    3. Form Request Validation.

    Creating Form Requests

    If you want to create a form request. It is custom request class that contain validation logic. We can create like this:-

    php artisan make:request StoreBlogPost
    

    The generated class will be placed in app/Http/Requests directory. if directory doesn't exists, it will be created when run the make:request command.

    public function rules()
    {
        return [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ];
    }
    

    Adding After Hooks To Form Requests

    You want to add an after hook to a form request, you can use withValidator
    method. Its allows you to call any of its methods before the validation rules.

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });
    }
    

    Authorizing Form Requests

    The form request class also contain an authorize method. You can check if the autheticated user actually has the authority to update a given resource.

    public function authorize()
    {
        $comment = Comment::find($this->route('comment'));
    
        return $comment && $this->user()->can('update', $comment);
    }
    

    route method:-

    Route::post('comment/{comment}');
    

    4. Manually Creating Validators.

    If you don't want to use the ValidatesRequests traits Validate method. You can create a validator instance manually using the validator facade method.

    Let's look at a simple example.

    all(), [
                'title' => 'required|unique:posts|max:255',
                'body' => 'required',
            ]);
    
            if ($validator->fails()) {
                return redirect('post/create')
                            ->withErrors($validator)
                            ->withInput();
            }
        }
    }
    

    Automatic Redirection

    If you want to create a validator instance manually but take advantage of the automatic redirection. Then you can use validate method on existing validator instance.

    Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ])->validate();
    

    Named Error Bags

    Error bags allow to pass the error message for a specific form. If you have multiple form in a single page then we use Errors bags. We can simply pass a name as a second argument to WithErrors.

    return redirect('register')
                ->withErrors($validator, 'login');
    

    You may access like this:-

    {{ $errors->login->first('email') }}
    

    After Validation Hook

    This method allows you to easily perform further validation and even add more error message to the message collection. You may use after method on a validator instance.

    $validator = Validator::make(...);
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
    
    if ($validator->fails()) {
        //
    }
    

    5. Working With Error Messages.

    The $error variable that is automatically made available to all views is also an instance of the MessageBag class. After calling the error method on a validator
    instance, you will recieve an Illuminate\Support\MessageBag instance.

    Retrieving The First Error Message For A Field

    To get the first error message for a given field. We can use first method.

    $errors = $validator->errors();
    
    echo $errors->first('email');
    

    Retrieving All Error Messages For A Field

    If you need to get an array of the given input. You may use get method.

    foreach ($errors->get('email') as $message) {
        //
    }
    

    If you are validating an array form field. You can get all of the messages for each of the array elements using the "*" character.

    foreach ($errors->get('attachments.*') as $message) {
        //
    }
    

    Retrieving All Error Messages For All Fields

    To get an array of all message for all fields, use all method.

    foreach ($errors->all() as $message) {
        //
    }
    

    Determining If Messages Exist For A Field

    If any message exist for given field, You can use has method.

    if ($errors->has('email')) {
        //
    }
    

    Custom Error Messages

    There are many way to specify custom message. First, you can pass the custom message as the third argument to the validator::make method.

    $messages = [
        'required' => 'The :attribute field is required.',
    ];
    
    $validator = Validator::make($input, $rules, $messages);
    

    The attributes placed-holder will be replaced by the actual name of the field under validation.

    $messages = [
        'same'    => 'The :attribute and :other must match.',
        'size'    => 'The :attribute must be exactly :size.',
        'between' => 'The :attribute must be between :min - :max.',
        'in'      => 'The :attribute must be one of the following types: :values',
    ];
    

    Specifying A Custom Message For A Given Attribute

    $messages = [
        'email.required' => 'We need to know your e-mail address!',
    ];
    

    Specifying Custom Messages In Language Files

    'custom' => [
        'email' => [
            'required' => 'We need to know your e-mail address!',
        ],
    ],
    

    Specifying Custom Attributes In Language Files

    'attributes' => [
        'email' => 'email address',
    ],
    

    6. Available Validation Rules.

    The list of all available validation rules and their function.

    7. Conditionally Adding Rules.

    Validating When Present

    In some condition, you want to run validation checks against a field only if field is present in the input array. Add the sometimes rule to your rule list.

    $v = Validator::make($data, [
        'email' => 'sometimes|required|email',
    ]);
    

    Complex Conditional Validation

    Sometimes you wish to add validation rules based on more complex conditional logic. Like: you have to required a given field only if another field has greater value than 100. Then you may need two fields to have a given value only when another field is present. First, create a validator instance with static rules.

    $v = Validator::make($data, [
        'email' => 'required|email',
        'games' => 'required|numeric',
    ]);
    

    Suppose our web application is for game collector. We can sometimes method on the validator instance.

    $v->sometimes('reason', 'required|max:500', function ($input) {
        return $input->games >= 100;
    });
    
    $v->sometimes(['reason', 'cost'], 'required', function ($input) {
        return $input->games >= 100;
    });
    

    8. Validating Arrays.

    Validating array based form input fields to validate that each e-mail in a given array input field is unique.

    $validator = Validator::make($request->all(), [
        'person.*.email' => 'email|unique:users',
        'person.*.first_name' => 'required_with:person.*.last_name',
    ]);
    

    You can use the "*" character when specifying your validation message in your language files.

    'custom' => [
        'person.*.email' => [
            'unique' => 'Each person must have a unique e-mail address',
        ]
    ],
    

    9. Custom Validation Rules.

    Laravel provides a variety of helpful validation rules to registering custom validation rules is using the extend method on the validator facade.

    Let's look at a simple example.

    
    

    You may also pass a class and method to the extend method

    Validator::extend('foo', 'FooValidator@validate');
    

    Defining The Error Message

    you will also need to define an error message for the custom rules.

    "foo" => "Your input was invalid!",
    
    "accepted" => "The :attribute must be accepted.",
    

    When creating a custom validation rule, you may sometime need to define custom place-holder for error message.

    Let's look at a simple example.

    public function boot()
    {
        Validator::extend(...);
    
        Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
            return str_replace(...);
        });
    }
    

    Implicit Extensions

    when an attribute being validated is not present or contains an empty value as defined by the required rule, normal validation rules, including custom extensions, are not run.

    $rules = ['name' => 'unique'];
    
    $input = ['name' => null];
    
    Validator::make($input, $rules)->passes();
    

    Full Example of Form Validation

    Here i am going to explain how to validate a complete form.

    Create a controller called RegistrationController.php by Artsian command.

    php artisan make:controller RegistrationController --plain
    

    Views Part:-[Registration.blade.php]

    Let's look at a simple example.

    
    
    @if (count($errors) > 0)
       
      @foreach ($errors->all() as $error)
    • {{ $error }}
    • @endforeach
    @endif
    Name
    User Name
    Password
    Email
    Mobile
    Date of Birth
    File Upload

    Controller Parts:-[RegistrationController.php]

    Let's look at a simple example.

    all());
           $this->validate($request,[
    	     'name'=>'required',
             'username'=>'required|max:8',
             'password'=>'required',
    		 'email'=>'required',
    		 'number'=>'required',
    		 'date_of_birh'=>'required',
    		 'attachment'=>'required'
          ]);
    	}
    }
    

    Route Part:-

    Route::get('/validation','RegistrationController@showform');
    Route::post('/validation','RegistrationController@validate2');
    
    Laravel Validation