Unit 1 Laravel
Unit 1 Laravel
Unit: I
Introduction to Laravel
Rajat Kumar
Course Details (Asst. Professor)
(B. Tech. 6th Sem) CSE Department
2/15/2024 2
Evaluation Scheme
PHPExtension:BCMath,Ctype,cURL,JSON,Mbstring,OpenSSL,PCRE,
PDOServer Configuration, Nginx, Laravel server management
service LaravelForge, Autoloader optimization, Optimizing
Configuration Loading, Optimizing Route Loading, Optimizing
View Loading, Debug Mode, Deploying With Vapor.
CO : 01. Apply the knowledge of PHP that are vital in understanding Laravel application
and analyze the concepts, principles and methods in current Server-side
technology to implement Laravel application over the web.
CO : 02. Explain, analyze and apply the role of Client-side scripting language like Vuejs in the
workings of the web and web applications.
CO : 03. Implementing and analyzing the concept of Larvel Faker and Authentication on
Laravel.
CO : 04. Understand the impact of web designing by database connectivity with different
databases in the current market place where everyone use to prefer electronic
medium for shoping, commerce, and even social life also.
CO : 05. Analyzing and Creating a functional website using Laravel and Vuejs and Deploying
and Optimizing Web Application using Forge / Vapor.
Create a catalogue entry for a simple design pattern whose purpose and application
PSO4 is understood.
CO1 3 - - -
CO2 3 3 - -
CO3 3 3 - -
CO4 3 3 - -
CO5 3 3 - -
To have life-long learning for up-skilling and re-skilling for successful professional career
PEO4
as engineer, scientist, entrepreneur and bureaucrat for betterment of society.
• Before begin progressing with this tutorial, we assume that we are familiar
with website development using PHP and MySQL also we should be
familiar with HTML, Core PHP, and Advance PHP. We have applied Laravel
version 5.1 in all the examples.
• https://www.youtube.com/watch?v=1onmPIe07yo&ab_channel=Bitfumes
• https://www.youtube.com/watch?v=AhM4nAxaTLo&ab_channel=StellaLi
• https://www.youtube.com/watch?v=AEVhRhD2Wk&ab_channel=MattSocha
• https://www.youtube.com/watch?v=DfslJ-kaZXA&ab_channel=GeekyShows
• Authentication
• User authentication is a common feature in web applications. Laravel eases designing
authentication as it includes features such as register, forgot password and send
password reminders.
• Innovative Template Engine
• Laravel provides an innovative template engine which allows the developers to create
the dynamic website. The available widgets in Laravel can be used to create solid
structures for an application.
• Effective ORM (Object Relational Mapper)
• Laravel contains an inbuilt ORM with easy PHP Active Record implementation. An
effective ORM allows the developers to query the database tables by using the simple
PHP syntax without writing any SQL code. It provides easy integration between the
developers and database tables by giving each of the tables with their corresponding
models.
Intact Security
• Application security is one of the most important factors in web application
development. While developing an application, a programmer needs to take
effective ways to secure the application. Laravel has an inbuilt web application
security, i.e., it itself takes care of the security of an application. It uses "Bcrypt
Hashing Algorithm" to generate the salted password means that the password is
saved as an encrypted password in a database, not in the form of a plain text.
Libraries and Modular
• Laravel is very popular as some Object-oriented libraries, and pre-installed libraries
are added in this framework, these pre-installed libraries are not added in
other php frameworks. One of the most popular libraries is an authentication
library that contains some useful features such as password reset, monitoring active
users, Bcrypt hashing, and CSRF (Cross-Site Request Forgery) protection. This
framework is divided into several modules that follow the php principles allowing
the developers to build responsive and modular apps
• Artisan
• Laravel framework provides a built-in tool for a command-line known as Artisan that
performs the repetitive programming tasks that do not allow the php developers to
perform manually. These artisans can also be used to create the skeleton code,
database structure, and their migration, so it makes it easy to manage the database
of the system. It also generates the MVC files through the command line. Artisan
also allows the developers to create their own commands.
• For managing dependencies, Laravel uses composer. Make sure you have a
Composer installed on your system before you install Laravel. In this chapter, you
will see the installation process of Laravel.
• You will have to follow the steps given below for installing Laravel onto your
system −
• Step 1 − Visit the following URL and download composer to install it on your
system.
• https://getcomposer.org/download/
• Step 2 − After the Composer is installed, check the installation by typing the
Composer command in the command prompt as shown in the following
screenshot.
• Step 3 − Create a new directory anywhere in your system for your new Laravel
project. After that, move to path where you have created the new directory and
type the following command there to install Laravel.
• The Laravel framework can be directly installed with develop branch which includes
the latest framework.
• Step 4 − The above command will install Laravel in the current directory. Start the
Laravel service by executing the following command.
• php artisan serve
• Step 5 − After executing the above command, you will see a screen as shown below −
• Step 6 − Copy the URL underlined in gray in the above screenshot and open that
URL in the browser. If you see the following screen, it implies Laravel has been
installed successfully.
• Application Structure
• App
• It is the application folder and includes the entire source code of the project. It
contains events, exceptions and middleware declaration. The app folder comprises
various sub folders as explained below −
• Console
• Console includes the artisan commands necessary for Laravel. It includes a directory
named Commands, where all the commands are declared with the appropriate
signature. The file Kernal.php calls the commands declared in Inspire.php.
• Events
• This folder includes all the events for the project.
• Events
• Events are used to trigger activities, raise errors or necessary validations and
provide greater flexibility. Laravel keeps all the events under one directory. The
default file included is event.php where all the basic events are declared.
• Console
• Console folder contains the artisan commands required for Laravel. It contains the
commands which are declared with the appropriate signature.
• Exceptions
• Exceptions folder contains the various exception handlers. It handles the exceptions
thrown by the Laravel project. The Exceptions directory contains the methods that
handle the exceptions.
• The Exceptions directory contains the file handle.php that handles all the exceptions.
• Http
• The http folder is a sub-folder of the app folder. It has sub-folders such as controllers,
middleware, and requests. Laravel follows the MVC architecture, so http includes
controllers, views, and requests.
• Where,
• Middleware: It is a sub-folder of the http directory. It provides a filter mechanism
and communication between request and response.
• Requests: It is a sub-folder of http which includes all the requests of an application.
• Providers
• The Providers directory is used to contain all the service providers that are required
to register events for core servers and provides configuration for Laravel
application.
• The above screen shows the structure of the bootstrap directory. It contains one
folder, i.e., cache and two files, app.php and autoload.php.
• All of the configuration files for the Laravel framework are stored in the config
directory. Each option is documented, so feel free to look through the files and get
familiar with the options available to you.
• These configuration files allow you to configure things like your database connection
information, your mail server information, as well as various other core
configuration values such as your application timezone and encryption key.
• Application Overview
• We can get a quick overview of your application's configuration, drivers, and
environment via the about Artisan command:
Environment Configuration
• Environment Variable Types
• Retrieving Environment Configuration
• Determining The Current Environment
• Encrypting Environment Files
• Environment Configuration
• It is often helpful to have different configuration values based on the environment
where the application is running. For example, you may wish to use a different cache
driver locally than you do on your production server.
• To make this a effective, Laravel utilizes the DotEnv PHP library. In a fresh Laravel
installation, the root directory of your application will contain a .env.example file
that defines many common environment variables. During the Laravel installation
process, this file will automatically be copied to .env.
APP_NAME="My Application"
• The second value passed to the env function is the "default value". This
value will be returned if no environment variable exists for the given key.
• use Illuminate\Support\Facades\App;
•
• $environment = App::environment();
• You may also pass arguments to the environment method to determine if the environment
matches a given value. The method will return true if the environment matches any of the
given values:
• if (App::environment('local')) {
• // The environment is local
• }
•
• if (App::environment(['local', 'staging'])) {
• // The environment is either local OR staging...
• }
• Encryption
• To encrypt an environment file, you may use the env:encrypt command:
• Running the env:encrypt command will encrypt your .env file and place the
encrypted contents in an .env.encrypted file. The decryption key is
presented in the output of the command and should be stored in a secure
password manager. If you would like to provide your own encryption key
you may use the --key option when invoking the command:
• The length of the key provided should match the key length required by the
encryption cipher being used. By default, Laravel will use the AES-256-CBC
cipher which requires a 32 character key. You are free to use any cipher
supported by Laravel's encrypter by passing the --cipher option when
invoking the command.
Topic :Routing
Routing in Laravel allows the students to route all your application
requests to its appropriate controller.
Routing is one of the essential concepts in Laravel. The main functionality of the
routes is to route all your application requests to the appropriate controller.
<?php
Route::get('/', function ()
{
return view ('welcome');
});
In the above case, Route is the class which defines the static method get().
The get() method contains the parameters '/' and function() closure. The '/'
defines the root directory and function() defines the functionality of the get()
method.
As the method returns the view('welcome'), so the above output shows the
welcome view of the Laravel.
<?php
Route::get('/example', function ()
{
return "Hello World";
});
• Required Parameters
• The required parameters are the parameters that we pass in the URL.
Sometimes you want to capture some segments of the URI then this can be
done by passing the parameters to the URL. For example, you want to
capture the user id from the URL.
<?php • Output
Route::get('/', function() • When we enter the URL "localhost/laravelproject/public/".
{
return "This is a home page";
}
);
Route::get('/about', function()
{
return "This is a about us page";
}
);
Route::get('/contact', function()
{
return "This is a contact us page";
}
);
• Suppose you want to specify the route parameter occasionally, in order to achieve
this, you can make the route parameter optional. To make the route parameter
optional, you can place '?' operator after the parameter name. If you want to
provide the optional parameter, and then make sure that you have also provided
the default value to the variable.
• When we do not pass any variable to the URL, then the output would be:
• When we pass 'akshita' in the URL, then the output would be:
• From the above outputs, we observe that the parameter we pass in the URL is
optional. As we have provided the default value to the parameter as Null, so if we
do not pass any parameter, it will return null. If we pass the parameter in the URL,
then the value of the parameter would be displayed.
Route::get('user/{name?}', function ($name = 'himani') {
return $name;
});
• In the above example, we have provided the default value as 'himani’.
• OUTPUT
Topic : Middleware
In this topic student understand that how Middleware provide a convenient
mechanism for inspecting and filtering HTTP requests entering your
application. For example, Laravel includes a middleware that verifies the user
of your application is authenticated.
Middleware acts as a layer between the user and the request. It means that when
the user requests the server then the request will pass through the middleware,
and then the middleware verifies whether the request is authenticated or not. If
the user's request is authenticated then the request is sent to the backend. If the
user request is not authenticated, then the middleware will redirect the user to
the login screen.
• Make a middleware
• Apply middleware
• Check condition in middleware
• Route middleware
Middleware can be either applied to all the URLs or some particular URLs.
Step 1: Open the kernel.php file. If we want to apply the middleware to all
the URLs, then add the path of the middleware in the array of middleware.
Step 2: Type the command php artisan serve in Git Bash Window.
Step 3: Open the CheckAge.php file, which you have created as a
middleware.
Step 4: Now, enter the URL 'http://localhost/laravelproject/public/'.
Controllers are used to handle the request logic within the single class, and
the controllers are defined in the "app/http/Controllers" directory.
namespace App\Http\functions1;
namespace App\Http\functions2;
Suppose we have to run the function having the name, i.e., RunQuery(). They
are available in different directories functions1 and functions2, so we can say
that namespace avoids the collision between the same function names.
'use' is used to import the class to the current file.
Step 1: Open the Git Bash Window and type the command
"php artisan make:Controller PostsController" in Git Bash Window to
create the Controller.
Step 2: Now move to your project and see whether the PostsController file
has been created or not. The path of the file is:
C:\xampp\htdocs\laravelproject\app\Http\Controllers
The code contains the class that extends the Controller class, but this class
does not contain the functions such as create, update, or delete. Now we
will see how to create the controller which contains some default
functions.
To create the Controller, we will first delete the PostsController.php from the
project, which we have created in the previous step.
C:\xampp\htdocs\laravelproject\app\Http\Controllers
The code contains the functions which are used to perform the various
operations on the resources such as:
In the above syntax, 'posts' contains all the routes, and 'PostController' is
the name of the controller. In this case, we do not need to specify the
method name such as @index as we did in get() method because create(),
store(), destroy() methods are already available in the PostController class.
Route::resource('posts','PostController');
'localhost/laravelproject/public/posts/create'.
Step 2: Add the code given below in web.php file to register routes:
route::resources(
['posts'=>'PostController',
'student'=>'StudentController']
);
The above screen shows that routes of both the PostController and
StudentController are registered.
Constructor Injection:
use App\Repositories\UserRepository;
class UserService
{
protected $userRepository;
public function
__construct(UserRepository
$userRepository)
{
$this->userRepository =
$userRepository;
}
use App\Repositories\UserRepository;
namespace App\Http\Controllers;
use App\Services\UserService;
• At its heart, Sail is the docker-compose.yml file and the sail script that is stored at
the root of your project. The sail script provides a CLI with convenient methods for
interacting with the Docker containers defined by the docker-compose.yml file.
Available Stacks
Livewire + Blade
When using Livewire, you may pick and choose which portions of
your application will be a Livewire component, while the remainder
of your application can be rendered as the traditional Blade
templates you are used to.
Inertia + Vue
• https://www.youtube.com/watch?v=ImtZ5yENzgE&ab_channel=freeCode
Camp.org
• https://www.youtube.com/watch?v=0yVDMcGp97g&list=PLjVLYmrlmjGfh
2rwJjrmKNHzGxCZwBsqj&ab_channel=WsCubeTech
• https://laravel.com/docs/4.2/introduction#:~:text=Laravel%20attempts%2
0to%20take%20the,developer%20without%20sacrificing%20application%
20functionality.
• https://www.tutorialspoint.com/laravel/laravel_overview.htm
• https://www.javatpoint.com/laravel
Students learnt:
• Basic Laravel
• Laravel Features
• Installation of Laravel
• Routing and their types
• Configuration of Laravel
• Laravel jetStream