UNIT 3 Laravel
UNIT 3 Laravel
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.
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.
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.
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.
Repository pattern:
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.
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-
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.
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.
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.
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.
<!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.
1. php artisan serve: Starts the built-in web server and makes your application
accessible from a browser.
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.
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.
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:
return $field;
}
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>
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.
By default, Laravel's built-in authentication system uses the email field for
registration and authentication.
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.
<div>
<label for="username">{{ __('Username') }}</label>
<input id="username" type="text" name="username" value="{{
old('username') }}" required autofocus>
</div>
4. Modify the validation rules Finally, modify the validation rules in the
RegisterController to include the new username field.
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.
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.
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.
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.
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
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.
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:
<button type="submit">Register</button>
</form>
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',
]);
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
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.
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.
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',
],
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
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
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."
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.
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.
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;
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;
You can find more information about Faker and its methods in the official
documentation: https://github.com/fakerphp/faker
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.
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:
This will create a new seeder class called UsersTableSeeder in the database/seeds
directory.
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;
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:
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.
• 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.
<?php
return [
'msg' => 'Exemple Laravel internationalisation.'
];
?>
Step 3 − Save German file at resources/lang/de/lang.php.
<?php
return [
'msg' => 'Laravel Internationalisierung Beispiel.'
];
?>
• 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
• http://localhost:8000/localization/fr
• Step 11 − The output will appear as shown in the following image.
• http://localhost:8000/localization/de
• Step 13 − The output will appear as shown in the following image.
• 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: