0% found this document useful (0 votes)
30 views66 pages

UNIT 3 Laravel

The document discusses Laravel authentication and the Laravel Faker PHP library. It covers topics like Laravel design patterns, the Laravel blade template engine, creating data seeders, and seeding data. It provides objectives and explanations of various Laravel concepts and features.

Uploaded by

chessclubniet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views66 pages

UNIT 3 Laravel

The document discusses Laravel authentication and the Laravel Faker PHP library. It covers topics like Laravel design patterns, the Laravel blade template engine, creating data seeders, and seeding data. It provides objectives and explanations of various Laravel concepts and features.

Uploaded by

chessclubniet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

UNIT 3

LARAVEL AUTHENTICATION & LARAVEL FAKER

Rajat Kumar Laravel with Veu.JS (ACSE0612)


4/20/2023 1
Unit III
Unit Content

• Laravel design patter, Laravel blade template engine, Artisan command,


Login with username or email, Register with username or email, Logout,
Validate request data (required, unique, etc..), Protecting Router, Password
Confirmation, Social & Other Authentication method, Show success /
Failure message, Faker PHP library, Create data seeder, Seed data,
Localisation, Model Factories.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 2


Unit Objective

• In this unit Student will learn Laravel Authentication.


• Laravel attempts to take the pain out of development by easing common
tasks used in the majority of web projects, such as authentication, routing,
sessions, and caching.
• Laravel aims to make the development process a pleasing one for the
developer without sacrificing application functionality.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 3


Topic Objective

• Topic :Laravel design patter


• Laravel design pattern aims to separate each algorithm into separate
components so that they can be reused or combined in other parts of the
application easily. This approach also brings flexibility and makes it easy to
change an algorithm system wide.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 4


Laravel design pattern

Every programming language has a specific design pattern. This is design pattern
categories into 6 parts.
1. Builder pattern
2. Factory pattern
3. Strategy pattern
4. Provider pattern
5. Repository pattern
6. Facade pattern

1.Builder pattern:
• The Builder pattern is one of the main design patterns of Laravel. It separates the
construction of a complex object from its representation so that the same
construction process can create different representations. A builder is good for
creating complex products.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 5


Laravel design pattern

Factory pattern:
The Factory pattern is a creational pattern that uses factory methods to deal with the
problem of creating objects by specifying their concrete classes. The factory is
responsible for creating objects, not the clients. Multiple clients can call the same
factory.
Let’s go with the example of a car. If we want to make a car, we need a lot of parts like
battery, radiator, brake, fuel tank, etc. To create those car parts, we need a factory.
Now, we can create those parts of our own. But it’s time-consuming and let’s think we
don’t want to wait that long instead of we want a quick process like we just want to
assemble a car.
We can contact different companies who sell those parts and buy from them. So, in
this case, those companies are the creator or factories.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 6


Laravel design pattern

Strategy pattern:
The strategy pattern is a behavioral pattern. Defines a family of interchangeable
algorithms. It always uses an interface. This means the implementation details remain
in separate classes. Its programs are to an interface, not an implementation.

The Strategy pattern provides a way to encapsulate different algorithms or behaviours


in separate classes, allowing developers to easily swap out one implementation for
another. This pattern is especially useful for building flexible and extensible
applications that can adapt to changing requirements

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 7


Laravel design pattern

Provider pattern:
The provider pattern is the core of the Laravel framework and the packages we use. It’s
a set of patterns for some essential services. It’s like a plug-in or packages into our
service.
It provides classes that we can use in our namespace. Suppose, we’re going to sell
Toyota’s car and want to create our franchise. Toyota will give us the way to build cars.
How we set up our warehouse, it’s totally up to us.
But, the ways of making all the cars, necessary car parts and all the paperwork they’ll
provide to us. So, in that case, they are the provider. In this case, our CarBuilder or
CarManager is provided by Toyota.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 8


Laravel design pattern

Repository pattern:

In simple words, the Repository pattern in a laravel application is a bond between


models and controllers. In this process, the model should not be responsible for
connecting with or retrieving data from the database. Therefore, to keep our code
clean and safe, it is necessary to use the repository. It reduces the duplication and
errors of our code.

Let’s think of an example, we have a customer table in our database, where we can
add, store, edit and delete customer data. We also have a Customer model. The idea is,
we’re going to create an interface and define some methods.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 9


Laravel design pattern

Facade pattern:
The facade pattern provides a combined interface to a set of interfaces in a subsystem.
A facade defines a higher-level interface that makes the subsystem easier to use.
The facade pattern isn’t all about covering up bad code, though. It can be used to
create a simple public interface that bonds multiple classes working together in some
way. Suppose you’re dealing with a large subsystem with hundreds of public methods
but you only need a few of them.

You want the facade to correctly construct the various classes in the subsystem and
provide those interfaces to you such that you can use them with ease. All of Laravel’s
facades are defined in the Illuminate\Support\Facades namespace. Let’s see an
example-

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 10


Laravel blade template engine

Laravel Blade is a powerful templating engine that is built into the Laravel
framework. It provides an easy-to-use syntax for defining templates, allowing
developers to quickly and easily create dynamic, reusable views for their
applications.

Blade templates are designed to be simple and easy to read, with a minimal
amount of syntax required to define them. They use a combination of
standard HTML code and Blade-specific directives, which are enclosed in
double curly braces ({{ }}) or the @ symbol.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 11


Laravel blade template engine

Blade templates offer a number of features, including:

1. Template inheritance, which allows you to define a base template that can
be extended by other templates.

2. Sections, which allow you to define blocks of content that can be overridden
by child templates.

3. Conditionals, loops, and other control structures, which allow you to add
dynamic behavior to your templates.

4. Layouts and includes, which allow you to reuse templates across multiple
pages.

5. Directives for outputting content, including escaped and unescaped output.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 12


Laravel blade template engine

The Laravel Blade template engine uses a simple and intuitive syntax for defining
templates. Here are some of the key syntax elements used in Blade

1. Echoing Data: To output data in a Blade template, you can use the double
curly braces syntax. For example, {{ $name }} would output the value of the
$name variable.

2. Control Structures: Blade templates provide a variety of control structures that


allow you to add dynamic behavior to your templates, including @if, @else,
@elseif, @foreach, @for, @while, and @switch. These are similar to their PHP
counterparts, but with a simpler and more intuitive syntax.

3. Template Inheritance: Blade templates support template inheritance, which


allows you to define a base template that can be extended by other templates.
You can define a section in the base template using the @yield directive, and
then override that section in a child template using the @section directive.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 13


Laravel blade template engine

4. Comments: Blade templates support both HTML and PHP-style comments.


HTML-style comments are enclosed in <!-- -->, while PHP-style comments are
enclosed in {{-- --}}.

5. Escaping Data: Blade templates automatically escape any data that is output
using the {{ }} syntax. If you need to output unescaped data, you can use the {!!
!!} syntax instead.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 14


Laravel blade template engine

<!DOCTYPE html>
<html>
<head>
<title>{{ $title }}</title>
</head>
<body>
<h1>{{ $heading }}</h1>
<p>{{ $body }}</p>
</body>
</html>

In this example, we're using the {{ }} syntax to output the values of three
variables: $title, $heading, and $body. This template could be used to generate
a simple HTML page with dynamic content.

Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 15


Topic Objective

• Topic :Artisan command


• Artisan is a command-line interface that Laravel provides which helps in
making the production process fast and easy. Laravel has its own Command
Line interface called Artisan.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 16


Artisan command

Artisan is the command-line interface included with Laravel that provides a


number of helpful commands for managing your Laravel application.

Artisan commands are used to perform a variety of tasks, such as generating


boilerplate code, running database migrations, and interacting with the
application's environment

Here are some examples of common Artisan commands:

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 17


Artisan command

1. php artisan serve: Starts the built-in web server and makes your application
accessible from a browser.

2. php artisan make:model: Generates a new model class in the app/Models


directory.

3. php artisan make:controller: Generates a new controller class in the


app/Http/Controllers directory.

4. php artisan make:migration: Generates a new database migration file in the


database/migrations directory.

5. php artisan migrate: Runs any pending database migrations.

6. php artisan tinker: Starts an interactive REPL shell for interacting with your
application's code and data.

7. php artisan route:list: Lists all of the registered routes for your application.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 18


Artisan command

In addition to these built-in commands, you can also create your own
custom Artisan commands using the make:command command.

This allows you to extend Artisan with your own custom functionality,
making it even more powerful and flexible.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 19


Login with username or email

In Laravel, you can allow users to login using either their email address or their
username by customizing the authentication system. By default, Laravel's built-in
authentication system uses the email field for authentication, but it's easy to
modify it to allow for username-based authentication as well.

Here's how you can allow users to login using either their email or username in
Laravel:

1. Modify the LoginController Open the LoginController located in


app/Http/Controllers/Auth directory, and add a new function called username()
that returns either the email or the username, depending on what the user
entered in the login form.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 20


Login with username or email

public function username()


{
$field = filter_var(request()->input('username_or_email'),
FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

request()->merge([$field => request()->input('username_or_email')]);

return $field;
}

In this example, we first check if the user entered an email address or a


username in the login form. If they entered an email address, we set the email
field to the value of the input field. Otherwise, we set the username field to the
value of the input field. We then return the name of the field that should be
used for authentication

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 21


Login with username or email

2. Update the login form Next, update the login form to include a field
for the user to enter either their email or username. You can do this by adding
a new input field to the login form that accepts either an email or a username.

<div>
<label for="username_or_email">{{ __('Username or Email') }}</label>
<input id="username_or_email" type="text" name="username_or_email"
value="{{ old('username_or_email') }}" required autofocus>
</div>

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 22


Login with username or email

3 Test the login functionality Now you can test the login functionality.

When a user logs in, they can enter either their email or their username in the
login form.

The username() function we defined in step 1 will automatically determine which


field to use for authentication based on what the user entered

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 23


REGISTER WITH USERNAME/EMAIL

By default, Laravel's built-in authentication system uses the email field for
registration and authentication.

However, it's easy to customize the registration process to allow users to


register with a username instead of an email address.

Here's how you can allow users to register with a username in Laravel:

1. Modify the user migration file Open the migration file that creates the users
table in your database. By default, the migration file includes an email field,
which is used for authentication. To allow users to register with a username,
you need to add a new username field to the table.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 24


REGISTER WITH USERNAME/EMAIL

Schema::create('users', function (Blueprint $table) {


$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique(); // Add this line
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 25


REGISTER WITH USERNAME/EMAIL

2. Modify the registration form Next, modify the registration form to


include a field for the user to enter their desired username. You can do this
by adding a new input field to the registration form.

<div>
<label for="username">{{ __('Username') }}</label>
<input id="username" type="text" name="username" value="{{
old('username') }}" required autofocus>
</div>

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 26


REGISTER WITH USERNAME/EMAIL

3. Modify the registration controller Open the RegisterController located in


app/Http/Controllers/Auth directory, and modify the create() function to
include the new username field in the request.

protected function create(array $data)


{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'], // Add this line
'password' => Hash::make($data['password']),
]);
}

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 27


REGISTER WITH USERNAME/EMAIL

4. Modify the validation rules Finally, modify the validation rules in the
RegisterController to include the new username field.

protected function validator(array $data)


{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'username' => ['required', 'string', 'max:255', 'unique:users'], // Add this
line
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 28


REGISTER WITH USERNAME/EMAIL

With these modifications, users can now register with a username instead of
an email address.

When a user logs in, they will be prompted to enter either their email or their
username in the login form, and Laravel will automatically determine which
field to use for authentication based on what the user entered.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 29


VALIDATION AND REQUEST OF DATA IN LARAVEL

In Laravel, you can use the validate() method to validate incoming request data.
This method is available in controllers and form request classes, and it allows you to
define validation rules for your request data.

Here's how to validate and retrieve data from a form in Laravel:

1 Define validation rules First, define the validation rules for your form data. You
can define these rules in a validation array in your controller or in a form
request class. Here's an example validation array that validates a user's name
and email address:

$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
]);
In this example, we are validating the name and email fields of the form. The
required rule ensures that the fields are not empty, the string rule ensures that the
fields are strings, the max rule sets the maximum length of the fields, and the
unique rule ensures that the email field is unique in the users table.
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 30
VALIDATION AND REQUEST OF DATA IN LARAVEL

2 Retrieve validated data Once the data is validated, you can retrieve the
validated data using the $validatedData variable that was created in the
previous step. You can then use this data to create a new user, save it to the
database, or perform any other actions that are necessary for your application.

$user = new User;


$user->name = $validatedData['name'];
$user->email = $validatedData['email'];
$user->save();
In this example, we are creating a new User object, setting the name and email
fields to the validated data, and saving it to the database.
You can also retrieve the input data using the input() method on the request
object:
$name = $request->input('name');
$email = $request->input('email');
This method retrieves the value of the name and email fields from the request
object, regardless of whether or not the data has been validated.
With these steps, you can validate and retrieve data from a form in Laravel.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 31


protecting routes

In Laravel, you can protect your routes by adding middleware to them.


Middleware is a way to filter HTTP requests and responses before they are
processed by your application. By using middleware, you can restrict access to
certain routes based on authentication, authorization, or other criteria.

Here's an example of how to protect a route in Laravel:


Define a route with middleware First, define a route that requires authentication
using the auth middleware:

Route::get('/dashboard', function () {
// Only authenticated users can access this route
})->middleware(['auth']);

In this example, we have defined a route for the /dashboard URI that can only be
accessed by authenticated users. The middleware(['auth']) method specifies that
the auth middleware should be applied to this route.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 32


protecting routes

2. Define middleware The auth middleware is included in Laravel by


default, but you can define your own middleware if you need custom
functionality. To define a middleware, create a new class that extends the
Middleware class:

namespace App\Http\Middleware;

use Closure;

class MyMiddleware
{
public function handle($request, Closure $next)
{
// Do something before the request is handled
$response = $next($request);
// Do something after the request is handled
return $response;
}
}
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 33
protecting routes

In this example, we have defined a new middleware called MyMiddleware. The


handle method is called for every request that passes through this middleware.
You can add your own logic to this method to perform custom checks or
modifications to the request or response.

3. Add middleware to route To add your custom middleware to a route,


you can specify the middleware in the middleware method when defining the
route:

Route::get('/dashboard', function () {

})->middleware(['auth', 'my-middleware']);
In this example, we have added the my-middleware middleware to the route in
addition to the auth middleware. Now, every request to this route will pass
through both middleware before being handled by the route function.
With these steps, you can protect your routes in Laravel using middleware. By
adding middleware to your routes, you can ensure that only authorized users
can access certain parts of your application.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 34


Password Confirmation

In Laravel, you can easily implement password confirmation for your forms using
built-in validation rules and methods.
Here's an example of how to implement password confirmation in a form:
1. Create a form with password confirmation field Create a form with two
password fields: one for the password and one for the password confirmation:

<form method="POST" action="/register">


@csrf
<label for="password">Password</label>
<input type="password" name="password" id="password">

<label for="password_confirmation">Confirm Password</label>


<input type="password" name="password_confirmation"
id="password_confirmation">

<button type="submit">Register</button>
</form>

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 35


Password Confirmation

In this example, we have created a simple form with two password fields:
password and password_confirmation.

The csrf token is included to protect against cross-site request forgery attacks.

2. Define validation rules Define validation rules for the form data. To require the
user to confirm their password, you can use the confirmed validation rule.

This rule checks that the value of the password_confirmation field matches the
value of the password field:

$validatedData = $request->validate([
'password' => 'required|string|min:8|confirmed',
]);

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 36


Password Confirmation

In this example, we have defined a validation rule for the password field that
requires it to be a string with a minimum length of 8 characters and to be
confirmed by the password_confirmation field.
3. Display validation errors If the validation fails, Laravel automatically redirects
back to the previous page and displays the validation errors. You can display the
errors in your view using the @error directive:

<label for="password">Password</label>
<input type="password" name="password" id="password">
@error('password')
<p>{{ $message }}</p>
@enderror

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 37


Password Confirmation

<label for="password_confirmation">Confirm Password</label>


<input type="password" name="password_confirmation"
id="password_confirmation">

In this example, we have added the @error directive to the password field to
display the validation error message if the validation fails.

With these steps, you can easily implement password confirmation in your
Laravel forms. By using built-in validation rules and methods, you can ensure
that the user enters their password correctly and avoid errors in your
application.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 38


social & other authentication methods

Laravel Socialite:
In addition to typical, form based authentication, Laravel also provides a simple,
convenient way to authenticate with OAuth providers using Laravel Socialite. Socialite
currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub,
GitLab, and Bitbucket.
Installation
To get started with Socialite, use the Composer package manager to add the package to
your project's dependencies:
composer require laravel/socialite

Upgrading Socialite
When upgrading to a new major version of Socialite, it's important that you carefully
review the upgrade guide.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 39


social & other authentication methods

Configuration
Before using Socialite, you will need to add credentials for the OAuth providers your
application utilizes. Typically, these credentials may be retrieved by creating a
"developer application" within the dashboard of the service you will be authenticating
with.
These credentials should be placed in your application's config/services.php
configuration file, and should use the key facebook, twitter (OAuth 1.0), twitter-oauth-2
(OAuth 2.0), linkedin, google, github, gitlab, or bitbucket, depending on the providers
your application requires:

'github' => [
'client_id' => env('GITHUB_CLIENT_ID'),
'client_secret' => env('GITHUB_CLIENT_SECRET'),
'redirect' => 'http://example.com/callback-url',
],

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 40


social & other authentication methods

Authentication
Routing
• To authenticate users using an OAuth provider, you will need two routes: one for
redirecting the user to the OAuth provider, and another for receiving the callback
from the provider after authentication. The example routes below demonstrate the
implementation of both routes.
• use Laravel\Socialite\Facades\Socialite;

• Route::get('/auth/redirect', function () {
• return Socialite::driver('github')->redirect();
• });
• Route::get('/auth/callback', function () {
• $user = Socialite::driver('github')->user();
• // $user->token
• });
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 41
social & other authentication methods

• The redirect method provided by the Socialite facade takes care of


redirecting the user to the OAuth provider, while the user method will
examine the incoming request and retrieve the user's information from the
provider after they have approved the authentication request.

• Authentication & Storage


• Once the user has been retrieved from the OAuth provider, you may determine if the
user exists in your application's database and authenticate the user. If the user does
not exist in your application's database, you will typically create a new record in your
database to represent the user:

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 42


social & other authentication methods

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
Route::get('/auth/callback', function () {
$githubUser = Socialite::driver('github')->user();
$user = User::updateOrCreate([
'github_id' => $githubUser->id,
], [
'name' => $githubUser->name,
'email' => $githubUser->email,
'github_token' => $githubUser->token,
'github_refresh_token' => $githubUser->refreshToken,
]);
Auth::login($user);
return redirect('/dashboard');
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 43
});
Topic Objective

• Topic :Show success / Failure message


• In this topic we will define various type of flash message notification like alert
success, alert danger, alert info, alert warning messages in bootstrap laravel 7
projects.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 44


Show success / Failure message

In Laravel authentication, there are several success and failure messages that
can be displayed to users during the authentication process.

Success messages:

When a user successfully logs in: "You have been logged in.“

When a user successfully logs out: "You have been logged out."

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 45


Show success / Failure message

Failure messages:

When a user enters incorrect login credentials: "These credentials do not match
our records."
When a user tries to access a protected route without being logged in:
"Unauthenticated."
When a user enters an incorrect password reset token: "This password reset
token is invalid."
When a user's account is suspended or banned: "Your account has been
suspended/banned."
When a user tries to reset their password but enters an incorrect email address:
"We can't find a user with that email address."
When a user tries to reset their password but enters an incorrect password
confirmation: "The password confirmation does not match."
These messages can be customized in the resources/lang directory of your
Laravel application, by modifying the auth.php language file.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 46


Faker PHP library

Faker is a PHP library that generates fake data for testing and development
purposes.

It is widely used in web application development to create test data for unit
testing, integration testing, and user acceptance testing.

Faker generates realistic-looking fake data, such as names, addresses, phone


numbers, email addresses, and more.

It is easy to use and highly customizable, allowing developers to generate data


that meets their specific requirements.

Here's an example of how to use Faker to generate fake data:

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 47


Faker PHP library

1. Install Faker You can install Faker using Composer:

composer require fakerphp/faker

2. Use Faker to generate fake data Here's an example of how to use Faker
to generate a fake name:

use Faker\Factory;

$faker = Factory::create();
$name = $faker->name;

echo $name;

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 48


Faker PHP library

This code creates a new instance of the Faker class, then uses the name method
to generate a fake name.
The output will be a random name, such as "John Doe".
You can use other methods provided by Faker to generate different types of fake
data, such as addresses, phone numbers, email addresses, and more.
For example, to generate a fake email address, you can use the email method:

$email = $faker->email;

echo $email;

This code generates a fake email address, such as "[email protected]".


Faker provides a wide range of methods for generating different types of fake
data.

You can find more information about Faker and its methods in the official
documentation: https://github.com/fakerphp/faker

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 49


Topic Objective

• Topic :Create data seeder


• Seed data is data that you populate the database with at the time it is created. You
use seeding to provide initial values for lookup lists, for demo purposes, proof of
concepts etc.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 50


Create data seeder

In Laravel, you can use seeders to populate your database with test data. Seeders
are classes that allow you to define data that you want to insert into your
database, and then run a command to execute the seeder and insert the data.

Here's an example of how to create a data seeder in Laravel:

1. Create the seeder class You can create a seeder class using the
make:seeder Artisan command. For example, to create a seeder for the users
table, run the following command:

php artisan make:seeder UsersTableSeeder

This will create a new seeder class called UsersTableSeeder in the database/seeds
directory.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 51


Create data seeder

2. Define the data to be seeded In the seeder class, you can use the
Eloquent ORM to define the data that you want to insert into your database. For
example, to insert a new user into the users table, you can use the following
code:

use Illuminate\Database\Seeder;
use App\User;

class UsersTableSeeder extends Seeder


{
public function run()
{
$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = bcrypt('password');
$user->save();
}
}
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 52
Create data seeder

In this example, we are creating a new User model instance and setting its name,
email, and password properties. We are then calling the save method to insert
the new user into the users table.

3. Run the seeder Once you have defined the data that you want to seed,
you can run the seeder using the db:seed Artisan command. For example, to run
the UsersTableSeeder seeder, run the following command:

php artisan db:seed --class=UsersTableSeeder

This will execute the run method of the UsersTableSeeder class and insert the
data into the users table.

You can create multiple seeders to populate your database with different types of
test data. Seeders are a useful tool for testing and development, as they allow
you to quickly populate your database with realistic-looking test data.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 53


Topic Objective

• Topic :Localisation
• Laravel's localization features provide a convenient way to retrieve strings in various
languages, allowing you to easily support multiple languages within your application.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 54


Localisation

Localization feature of Laravel supports different language to be used in application.


You need to store all the strings of different language in a file and these files are stored
at resources/views directory. You should create a separate directory for each supported
language. All the language files should return an array of keyed strings as shown below.
<?php
return [
'welcome' => 'Welcome to the application'
];
Example
Step 1 − Create 3 files for languages − English, French, and German. Save English file at
resources/lang/en/lang.php
<?php
return [
'msg' => 'Laravel Internationalization example.'
];
?>
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 55
Localisation

Step 2 − Save French file at resources/lang/fr/lang.php.

<?php
return [
'msg' => 'Exemple Laravel internationalisation.'
];
?>
Step 3 − Save German file at resources/lang/de/lang.php.

<?php
return [
'msg' => 'Laravel Internationalisierung Beispiel.'
];
?>

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 56


Localisation

hbStep 4 − Create a controller called LocalizationController by executing the following


command.
php artisan make:controller LocalizationController --plain
Step 5 − After successful execution, you will receive the following output −hb

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 57


Localisation

• Step 6 − Copy the following code to file


• app/Http/Controllers/LocalizationController.php
• app/Http/Controllers/LocalizationController.php
• <?php
• namespace App\Http\Controllers;
• use Illuminate\Http\Request;
• use App\Http\Requests;
• use App\Http\Controllers\Controller;
• class LocalizationController extends Controller {
• public function index(Request $request,$locale) {
• //set’s application’s locale
• app()->setLocale($locale);
• //Gets the translated message and displays it
• echo trans('lang.msg');
• }
4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 58
• }
Localisation

• Step 7 − Add a route for LocalizationController in app/Http/routes.php file. Notice


that we are passing {locale} argument after localization/ which we will use to see
output in different language.

• app/Http/routes.php

• Route::get('localization/{locale}','LocalizationController@index');
• Step 8 − Now, let us visit the different URLs to see all different languages. Execute the
below URL to see output in English language.

• http://localhost:8000/localization/en

• Step 9 − The output will appear as shown in the following image.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 59


Localisation

• Step 10 − Execute the below URL to see output in French language.

• http://localhost:8000/localization/fr
• Step 11 − The output will appear as shown in the following image.

• Step 12 − Execute the below URL to see output in German language

• http://localhost:8000/localization/de
• Step 13 − The output will appear as shown in the following image.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 60


Topic Objective

• Topic :Model Factories


• Laravel Model Factories provide a convenient way to populate your database with
Dummy Data during development as well as provide a way to insert Records while
running Tests.

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 61


Model Factories

• Starting
• Let’s start by creating a new project named Factories. To do this, run the following
command:
• laravel new Factories
• This will create a new Laravel project within a folder named Factories.
• Creating a new Model
• Now, let’s create a Post model and a migration for it. To do this run the following
command from the project root directory:
• php artisan make:model Post -m
• This command will create a new Post model and because we added -m or --migration
flag, it will create a migration for it as well. This command will create two files at
app/Post.php and database/migrations/create_posts_table.php. Create posts table
relationship with the user by opening app/User.php and defining the following
relation:

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 62


Model Factories

public function posts()


{
return $this->hasMany(Post::class);
}
Setting up Database
Now, go to your .env file and change credentials for your database. Since it is just a
dummy project, I will go with SQLite. To use SQLite, set DB_CONNECTION to sqlite and
remove all other DB_* lines from your .env. Your .env database part now look like this:
DB_CONNECTION=sqlite
Now that you have set DB_CONNECTION to sqlite, create a file named database.sqlite
in your database directory in the root of your application. Also, run the following
command to configure your cache.

php artisan config:cache

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 63


Daily Quiz

1. CLI Command to migrate in Laravel project?


• php artisan create migration
• php artisan migrate
• php artisan serve
• None of the above

2. By default laravel project runs on which PORT?


• 3000
• 5000
• 8000
• 7000

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 64


Daily Quiz

3. Where is the routing file located in Laravel ?


• app/Http/
• routes/
• urls/
• vendors/

4. Which directory contain “robot.txt” file ?


• app
• public
• config
• storage

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 65


Daily Quiz

5. Where do we need to set database connection in Laravel?


• config.php
• setting.php
• In seed files
• .ENV file

6. Can laravel application support caching?


• Yes
• No
• Can't Say
• None of these

4/20/2023 Rajat Kumar Laravel with Veu.JS (ACSE0612) Unit III 66

You might also like