My Laravel PDF 1708710166
My Laravel PDF 1708710166
{{ الر ِحيم ِ
َّ الل ِـه }} ِِب ْس ِم
1
1) What is Laravel framework?
2) What are the basic concepts in laravel?
3) What are the features of Laravel?
4) Composer?
5) Composer.lock and Composer.json?
6) What is Blade?
7) Artisan?
8) How to define environment variables in Laravel?
9) Can use Laravel for Full Stack Development (Frontend + Backend)?
10) What is the maintenance mode?
11) Controller?
12) What are the default route’s files in Laravel?
13) How to define routes in Laravel?
14) What is reverse Routing?
15) What is the difference between authentication and authorization?
16) What are policies classes?
17) Explain what are gates in Laravel?
18) What is Auth? How is it used?
19) What is Middleware?
20) Define Laravel guard.
21) Explain traits in Laravel.
22) CSRF Protection?
23) Request and Response?
24) How to do request validation in Laravel?
25) What is the difference between the Get and Post method?
26) Which class is used to handle exceptions?
27) Define hashing in Laravel.
28) Explain the concept of encryption and decryption in Laravel.
29) What are common HTTP error codes?
30) Models?
31) When will you use fillable or guarded?
32) What is Eloquent in Laravel?
33) What is query scope?
2
34) Migrations?
35) Seeders?
36) Factories?
37) How to implement soft delete in Laravel?
38) Session and Cookie?
39) What is Tinker?
40) How do you check the installed Laravel version of a project?
41) What is pagination?
42) Laravel Eloquent skip () and take() Query?
43) What is the namespace in Laravel?
44) What is PSR-4 autoloading standard?
45) Name some common tools used to send emails in Laravel.
46) What is the use of dd() function?
47) What are Closures in Laravel?
48) What are Relationships in Laravel?
49) Explain MVC Architecture
50) What is throttling and how to implement it in Laravel?
51) What is modular?
52) What is the difference between class and component?
53) Request Lifecycle?
54) Explain the function of Console Kernel
55) What is a service, service container and service provider in Laravel?
56) What is the register and boot method in the Service Provider class?
57) What are facades?
58) What are macro functions?
59) How to mock a static facade method in Laravel?
60) Explain logging in Laravel?
61) How to enable query log in laravel
62) What is the process of clearing cache in Laravel?
63) What are Events in Laravel?
64) What is Localization in Laravel?
65) What are collections?
66) What are contracts?
3
67) What is the queue in Laravel?
68) What are accessors and mutators?
69) What is socialite in Laravel?
70) Task Scheduling?
71) What is socialite in Laravel?
72) What is Sitemap in Laravel?
73) What is mocking in Laravel?
74) What is the Repository pattern in laravel?
75) What is the Singleton design pattern in laravel?
76) What php laravel observer design pattern?
77) How can we reduce memory usage in Laravel?
78) What is a lumen?
79) What is Laravel Nova?
80) What is the use of Bundles in Laravel?
81) Debug mode?
82) Deploying with Forge/ Vapor
4
1)What is Laravel framework?
It’s a PHP framework created by Taylor Otwell with a great goal in mind. Keep it simple and
clear.
Laravel solves some very basic stuff for developers like routing, ORM, authentication.
The framework is well documented and the code itself is well thought out.
Laravel has a huge community, not only developers but also people who write articles or create
videos, there are a lot of tutorials you can find all over the internet. Every problem has multiple
solutions, uses a lot of third-party components to provide additional functionality and
development processes. These components are typically open-source libraries or packages
developed by the Laravel community or other developers.
Laravel follows the "composer" dependency management system, which allows developers to
easily include and manage third-party components in their projects. Composer is a PHP package
manager that handles the installation, autoloading, and updating of dependenciesHere are
some ways Laravel utilizes third-party components:
In Laravel, third-party components refer to external libraries or packages that are not part of
the Laravel framework itself but can be integrated into Laravel applications to provide
additional functionality.
Symfony Components:
Laravel uses several components from the Symfony framework, such as
• HttpFoundation component: this component provides a set of classes and methods that
make it easier to handling HTTP requests and responses, managing sessions and cookies,
symfony http_foundation document , symfony-httpfoundation devdojo
• Routing component for defining application routes
• Validator component for data validation.
Database Libraries:
Laravel supports multiple database systems, including MySQL, PostgreSQL, SQLite and SQL
Server. It utilizes third-party libraries like Doctrine DBAL (Database Abstraction Layer).
5
Template Engines:
Laravel includes the Blade template engine by default which provides a simple syntax for
creating views, Blade itself is a component developed specifically for Laravel, there are several
third-party template engines that you can use in Laravel based on your project requirements
such as: Twig, Smarty, Plates.
Laravel uses third-party libraries like symfony/security for handling authentication and
authorization processes. This library provides features like user authentication, password
hashing, and access control.
Queueing Systems:
While building your web application, you may have some tasks, such as parsing and storing an
uploaded file, that take too long to perform during a web request. Thankfully, Laravel allows you
to easily create queued jobs that may be processed in the background.
6
Laravel supports multiple queueing backends, including beanstalkd, Amazon SQS, Redis or a
relational database.
Testing: Laravel encourages developers to write automated tests for their applications. It
integrates with popular testing frameworks like PHPUnit and Behat, allowing developers to
easily write and execute tests.
Utility Libraries: Laravel includes various libraries for tasks like working with files, generating
URLs, handling events, sending emails, and more. Many of these utilities are third-party
component
------------------------------------------------------------------------------------------------------------------------------
• Blade Templating
• Routing
• Eloquent ORM
• Middleware
• Artisan(Command-Line Interface)
• Security
• In-built Packages
• Caching
• Service Providers
• Facades
• Service Container
7
• Libraries & Modular.
• Unit Testing.
• Security.
------------------------------------------------------------------------------------------------------------------------------
4)Composer?
Composer refers to a dependency management tool designed for PHP projects, including
Laravel itself like Node.js use npm(node package manager) and Ruby use Bundler package
manager to install, remove, update packages.
Composer is used to manage the packages that Laravel application depends on, allows you to
define the packages in a file called composer.json. It ensures that the correct versions of the
dependencies are installed.
-----------------------------------------------------------------------------------------------------------------------------
• composer.lock:
Generated automatically by Composer after running composer install or composer update.
It acts as a lock file, freezing the versions of all your project's dependencies at the time of
installation.
8
This file ensures that your project will always use the same versions of the dependencies across
different environments and when deploying to different servers.
The format is machine-readable and not intended for manual editing.
• In summary:
composer.json: Describes what dependencies you need.
composer.lock: Ensures you get the exact versions you need, consistent across environments.
------------------------------------------------------------------------------------------------------------------------------
6)What is Blade?
Blade is a PHP template engine built into Laravel. When building a Laravel app, your HTML code
is written into the blade file which is saved with name.blade.php extension. The Features:
1) Clean code (easy to use, readable)
2) separate business logic from the user interface (UI)
In the above code, the index method retrieves the users from the database and passes them to
the users.index view for rendering. By separating the business logic from the UI, the controller
is responsible for retrieving the users and passing them to the view, while the Blade template
focuses on presenting the data in a structured way.
9
3) Template Inheritance:
Blade allows you to define a master layout and extend it across multiple views. This feature
helps in reusing the code by separating common sections (such as headers and footers) into the
master layout while allowing child views to override specific sections as needed.
Suppose you have a master layout called layouts.app that defines the structure of your
application's pages
In this example, the @yield('content') directive is a placeholder that will be replaced by the
actual content of the child views.
Now, let's say you have a specific view, such as a contact.blade.php, which inherits the master
layout and adds its own content
In the contact.blade.php template, the @extends('layouts.app') directive specifies that this
view extends the layouts.app master layout. The @section('content') directive defines the
Content section named 'content' that will replace the @yield('content') placeholder in the
master layout.
4) Control Structure:
10
In Laravel's Blade template engine, control structures provide a convenient way to render
content over arrays and collections. Here are some examples of control structures in Blade.
Conditional Statements (@if, @else, @elseif, @unless), Empty Check (@empty, @isset,
@unlessempty), Loop Control (@break, @continue), Looping Structures (@for, @foreach,
@while)
5) Template Includes:
Blade allows you to include other Blade templates within your views using the `@include`
directive. This allows you to reuse common components across multiple views.
11
In this example, the @include('header') directive is used to include the header.blade.php
template within the home.blade.php view. When the view is rendered, the content of the
header.blade.php template will be inserted at the specified location.
6) Comments:
Blade provides easy ways to add comments to your templates
7)Escaping:
In Laravel, the Blade template engine automatically escapes output by default, which helps
prevent cross-site scripting (XSS) attacks. When you output data in a Blade template, Laravel
ensures that any HTML tags or special characters are rendered as plain text rather than being
interpreted as HTML,
12
the HTML tags and special characters (<, >) have been encoded as their corresponding HTML
entities (<, >), preventing them from being interpreted as actual HTML tags or JavaScript.
By escaping output by default, Laravel helps protect your application from potential XSS attacs
by ensuring that user-supplied data is treated as plain text and not executed as code.
However, there may be scenarios where you want to output raw, unescaped HTML content. In
such cases, you can use the {!! !!} syntax in Blade templates. For example:
<p>Welcome, {!! $name !!}</p>
In this case, the value of $name will be output as raw HTML, without any automatic escaping.
------------------------------------------------------------------------------------------------------------------------------
7) Artisan?
In the context of the Laravel framework, the term "artisan" refers to a command-line interface
tool which provides a range of helpful commands for managing and developing Laravel
applications, to use artisan, you open your command-line interface, navigate to your Laravel
project directory, and run php artisan followed by the desired command. For example:
• Every command also includes a "help" screen which displays and describes the
command's available arguments and options.
php artisan help migrate
• generate controller
php artisan make:controller UserController
13
you can define environment variables in the .env file. The .env file is used to store configuration
values for your application, including database credentials, API keys, and other sensitive
information.
Laravel provides a convenient way to access environment variables using the env () helper
function. For example, you can retrieve the value of the `DB_CONNECTION` variable using:
$dbConnection = env('DB_CONNECTION');
----------------------------------------------------------------------------------------------------------------------------- -------------
------------------------------------------------------------------------------------------------------------------------------
When maintenance mode is enabled, HTTP returns a response that "503 Service Unavailable",
indicating to users that the application is currently undergoing maintenance. During this time,
you can display a customized maintenance page or message to inform users about the ongoing
maintenance and when they can expect the application to be available again.
To enable maintenance mode,
you can use the down Artisan command provided by Laravel
14
php artisan down
This command creates a `down` file in the storage directory of your Laravel project, indicating
that the application is in maintenance mode.
11) Controller?
15
controller is a class that receives incoming HTTP requests, processes the data, and generates
the appropriate response. Controllers are an essential part of the Laravel framework, placed in
the app/Http/Controllers directory. Responsibilities of a Laravel Controller:
• Receive HTTP requests: Controllers capture incoming HTTP requests, including the URL,
HTTP method (GET, POST, PUT, DELETE), and request data (headers, body parameters,
cookies).
• Process request data: Controllers extract and process the data from the request, such as
validating user input, accessing database records.
• Generate responses: Controllers generate the responses based on the request and
processed data. This can include sending JSON or XML data, rendering Blade templates,
or redirecting to other routes.
• Interact with models: Controllers communicate with Laravel models to retrieve, create,
update, or delete data from the database.
• Encapsulate application logic: Controllers encapsulate the business logic of an
application, keeping the code organized and maintainable.
There are three main types of controllers in Laravel:
basic, Single Action and Resource controllers.
1) Basic Controllers
They are used to handle any type of request, and they can contain any number of methods.
Basic controllers are typically created using the make:controller Artisan command. For example,
16
Controllers that only have a single method to handle a specific action. This is useful when you
don’t require multiple methods in a controller. Here's an example to create a Single Action
Controller, Run the following command to generate a Single Action Controller:
When the request is made, Laravel will automatically invoke the __invoke() method in the
MySingleActionController class and execute the logic within it.
3) Resource Controllers:
are a type of controller that is designed to handle CRUD (Create, Read, Update, Delete)
operations on a resource. are typically created using the make:controller Artisan command with
the -r flag. For example, the following command will create a new resource controller
17
18
This controller contains seven methods: index(), create(), store(), show(), edit(), update(), and
destroy().
These methods handle the CRUD operations for the User model for example.
------------------------------------------------------------------------------------------------------------------------------
2) api.php: This file contains routes specifically designed for API endpoints. It includes
routes for handling API requests and responses. These routes are focused on providing
data to clients.
3) console.php: This file contains routes for registering commands in Laravel. It allows you
to define custom commands and their corresponding actions.
4) channels.php: For registering all your event broadcasting channels that your application
supports.
19
13) How to define routes in Laravel?
Routes define the URL that your application responds to the corresponding actions that should
be taken when a specific URL is accessed.
To define routes in Laravel, you can use the Route facade which provides methods for various
HTTP verbs such as get, post, put, patch, and delete. Here's an example of a basic route
definition:
In this example, when the /home URL is accessed via an HTTP GET request, the function will be
executed, and the string "Welcome to the home page!" will be returned as the response
Named routes allow you to assign a unique name to a route, making it easier to refer to the
route in your application's code.
return redirect()->route('user.profile');
Route groups provide a way to group related routes together, allowing you to apply shared
attributes or middleware to multiple routes at once. You can define a route group using the
Route::group method, specifying the common attributes or middleware within the callback
function. Here's an example:
20
In this example, both the /dashboard and /profile routes are within the auth middleware group,
meaning the user must be authenticated to access these routes.
This single line of code will generate routes for all the standard CRUD operations (index, create,
store, show, edit, update, and destroy) for the PostController controller. You can then
implement the corresponding methods in your controller to handle the logic for each
operation.
------------------------------------------------------------------------------------------------------------------------------
Instead of hardcoding URLs in your views or controllers, you can use reverse routing to
generate the URLs dynamically.
This approach ensures that your code remains flexible and easy to maintain, even if the URL
structure of your application changes.
21
The route () function takes the route name as the argument and returns the URL associated
with that route.
In this example, it will generate the URL /users.
In this example, the route () function includes an array of parameters for the route.
• name of route
• value of the id parameter
The generated URL will be /users/1.
------------------------------------------------------------------------------------------------------------------------------
15)What is the difference between authentication and
authorization?
• Authentication:
What it is: It's the process of verifying a user's identity. In simpler terms, it's about checking if a
user is who they say they are.
Example: Imagine logging into a website. You enter your username and password.
Authentication checks if these credentials match a real user in the database. If they do, you're
authenticated and granted access.
22
• Authorization:
What it is: Once a user is authenticated, authorization determines what they can do within the
application. It controls their access to specific resources and actions.
Example: Even though you're logged in, you might not be allowed to edit posts.Authorization
checks your permissions and grants or denies access.
Laravel provides two primary ways of authorizing actions: gates and policies.
------------------------------------------------------------------------------------------------------------------------------
In Laravel, policy classes are used for authorization and access control.
They define the rules and permissions that determine whether a user is authorized to perform
certain actions on a resource.
Policy classes allow you to centralize your authorization logic and make it more maintainable.
23
In this example, the PostPolicy class contains two methods:
view () and update (), Each method receives a User object and a Post object as parameters.
The methods define the authorization rules for viewing and updating a post.
24
In the AuthServiceProvider, we register the PostPolicy class. By associating the Post model with
its policy class, Laravel knows which policy to apply when performing authorization checks on
Post instances.
In the PostController, we use the authorize() method to perform authorization checks using the
policy.
The authorize() method checks if the currently authenticated user is authorized to perform a
specific action on the given resource (in this case, a Post).
25
17)Explain what are gates in Laravel?
In Laravel, gates are a way to define authorization rules that determine whether a user is
allowed to perform actions within your application.
gates provide a simple way to handle authorization logic.
gates are defined within the boot method of the App\Providers\AuthServiceProvider class using
the Gate facade.
A gate consists of a callback function that determines if a user is authorized to perform a
specific action. The callback function receives the authenticated user and any additional
parameters related to the action being performed. It then returns a boolean value indicating
whether the user is authorized or not.
In this example,
we define a gate named 'update-post'. The gate's callback function receives the authenticated
user and a $post object as parameters.
The callback checks if the user's ID matches the user_id of the post.
If they match, it returns true, indicating that the user is authorized to update the post.
In this example,
26
we use the Gate::allows() method to check if the authenticated user is authorized to update the
given $post.
If the gate allows the action, we can proceed with the update operation. Otherwise, we handle
the case where the user is not authorized.
Gates can be used in controllers, views, or anywhere else in your application where you need to
perform authorization checks.
------------------------------------------------------------------------------------------------------------------------------
18)What is Auth? How is it used?
In Laravel, the Auth class provides a convenient way to handle user authentication and
authorization.
Laravel provides two primary ways of authorizing actions: gates and policiespolicies.
The Auth class is used in controllers, views, or middleware to perform authenticate operations.
It offers various methods to authenticate users,
• check if a user is authenticated
• retrieve the authenticated user
• handle user logout.
Registration and Login:
With the authentication users can register and log in to your application using the provided
registration and login forms.
Protecting Routes:
To protect routes that require authentication, you can use the auth middleware.
This middleware ensures that only authenticated users can access the specified routes.
For example, in your route definition:
In this example, the /dashboard route is protected by the auth middleware, which means only
authenticated users can access it.
27
The Auth::user () method retrieves the authenticated user instance. You can then access the
user's properties, such as their name or email.
Logging Out:
To log out a user, you can use the Auth facade's logout() method.
For example, in a controller method:
The Auth::logout() method clears the authenticated user's session and logs them out.
------------------------------------------------------------------------------------------------------------------------------
19) What is Middleware?
Laravel provides a way to filter the entering HTTP requests to your application. middleware is a
layer of code that sits between the incoming request and the application's routes. It allows you
to intercept the request, perform any necessary processing, and then pass the request to the
next middleware in the stack.
Middleware is a powerful tool that can be used to perform a variety of tasks, such as
authentication and authorization.
Creating Middleware
To create middleware in Laravel, you can use the make:middleware Artisan command. For
example, the following command will create a new middleware class called AuthMiddleware:
28
This command will place a new file called AuthMiddleware.php in the
app/Http/Middleware directory. This file will contain the following code:
This middleware class will redirect any user who is not logged in to the login page.
Registering Middleware
Once you have created a middleware class, you need to register it with the application. You can
do this by adding the middleware class to the $middleware property of the Kernel class
App\Http\Kernel. For example, the following code will register the AuthMiddleware class with
the application:
This means that only users who are logged in will be able to access the /profile route.
------------------------------------------------------------------------------------------------------------------------------
In this example,
30
we have two guards defined: web and api.
The web guard is configured to use the session driver and the users provider.
The api guard, on the other hand, uses the token driver and the users provider.
The auth middleware is applied to each route group, specifying the guard that should be used
for authentication.
The web guard is used for web routes, while the api guard is used for API routes.
Authenticate Users:
In this example,
31
we have a login() method in a UserController that attempts to authenticate a user using the
web guard.
The attempt() method checks the provided credentials against the user records in the users
provider associated with the web guard.
If the authentication is successful, you can perform further actions. Otherwise, you can handle
the authentication failure accordingly.
------------------------------------------------------------------------------------------------------------------------------
21)Explain traits in Laravel.
In Laravel, traits are a way to encapsulate reusable code that can be easily shared across
multiple classes.
Traits provide a mechanism for code reuse in PHP without the need for inheritance.
Here's a simple example to illustrate the use of traits in Laravel:
In this example,
we have the Auditable trait with the createdBy() and createdAt() methods,
The Post class uses the Auditable trait by using the use keyword.
Inside the getPostInfo() method of the Post class, we can access the methods from the trait
using $this.
We call $this->createdBy() and $this->createdAt().
22) CSRF Protection?
32
CSRF (Cross-Site Request Forgery) protection is a security feature in Laravel that helps prevent
unauthorized requests from being submitted to your application.
Laravel automatically generates and verifies CSRF tokens for all incoming requests that modify
state (e.g., POST, PUT, DELETE requests) to ensure they come from your application and not
from a malicious source.
Here some examples of how use CSRF protection in Laravel:
Laravel includes the VerifyCsrfToken middleware by default, which is responsible for verifying
the CSRF token on incoming requests. This middleware is already registered in the global
middleware stack, so you don't need to add it manually.
To protect your forms from CSRF attacks, include the CSRF token in your form templates.
Laravel provides a convenient way to generate the CSRF token using @csrf directive within your
form tag.
------------------------------------------------------------------------------------------------------------------------------
23) Request and Response?
In Laravel, the Request and Response classes are used to handle incoming HTTP requests and
generate HTTP responses ... Handling a Request:
In this example, we define a route /example that expects a GET request. The route closure
function accepts an instance of the Request class as a parameter. We can access the incoming
request data, such as query parameters or form inputs, using the $request object. In this case,
we retrieve the value of the name parameter using the input() method ...
33
Generating a Response:
In this example, we define a route /example that also expects a GET request. Inside the route
closure function, we create an instance of the Response class, passing the response content,
status code, and headers as arguments. We can customize the response as needed. Finally, we
return the response object, which Laravel will handle and send back to the client.
------------------------------------------------------------------------------------------------------------------------------
24)How to do request validation in Laravel?
In Laravel, you can perform request validation using form requests.
Form requests provide a convenient way to validate incoming HTTP requests before they reach
your controller. Here's an example:
• Create a Form Request:
In this example, we create a StorePostRequest form request class by command php artisan
make:request StorePostRequest.
The authorize() method determines whether the user is authorized to make the request
The rules() method defines the validation rules for the incoming request data.
34
• Use the Form Request in your Controller:
In your controller, you type-hint the StorePostRequest form request class in the method where
you want to perform validation.
In this example, the store() method will only be executed if the request passes the validation
rules defined in the form request.
You can access the validated data using the validated() method on the form request instance.
If the incoming request fails validation, Laravel will automatically redirect the user back to the
previous page with the validation errors.
You can display the errors in your views using the $errors variable.
35
Laravel takes care of the error redirection and displaying the errors for you, based on the
validation rules defined in the form request.
------------------------------------------------------------------------------------------------------------------------------
• GET Method:
GET is used to retrieve data from the server.
The data is appended to the URL in the form of query parameters.
GET requests can be bookmarked and cached by browsers.
GET requests should not have any side effects on the server, meaning they should not modify
data.
GET requests have limitations on the length of the URL and the amount of data that can be
sent.
Here's an example,
URL: https://example.com/api/users?id=123
In this example, the query parameter id is set to 123, and the server is expected to return user
data for the given ID.
• POST Method:
POST is used to submit data to the server.
The data is sent in the request body and is not visible in the URL.
POST requests are not cached or bookmarked by browsers.
POST requests can have side effects on the server, such as creating, updating, or deleting data.
POST requests have no limitations on the length of the URL or the amount of data sent.
Here's an example,
URL: https://example.com/api/users
Body: {"name": "John", "email": [email protected]}
Here, the bcrypt function is used to generate the hash of the password, and then the hashed
value is stored in the password field of the User model.
37
The Hash::check method takes the plain-text password and the stored hashed password as
arguments and returns true if they match, and false otherwise.
------------------------------------------------------------------------------------------------------------------------------
28)Explain the concept of encryption and decryption in
Laravel
Encryption:
Encryption is the process of encoding information so that it can’t be understood
Before you get started, you need to make sure that you have an App Key generated.
If you do not have a key already generated, you can run the following command:
------------------------------------------------------------------------------------------------------------------------------
30) Models?
model represents a database table. It is responsible for interacting with the corresponding
database table and performing operations, such as retrieving, storing, updating, and deleting
38
data. Laravel follows the Model-View-Controller (MVC) architectural pattern, where models
represent the data layer.
To create a model in Laravel, you typically use the Artisan command-line tool by running the
command php artisan make:model ModelName, you can generate a new model file in the app
directory. php artisan make:model ModelName –m you can generate a new model with new
migration file in the `database/migrations` directory
Once the model is created, you can define its relationships with other models using Eloquent,
Laravel's built-in Object-Relational Mapping (ORM) system.
table: This property specifies the name of the database table associated with the model. By
convention, Laravel assumes that the table name is the plural form of the model's class name.
For example, if the model is named User, Laravel will expect the table name is users. However,
you can override this convention by setting the table property in your model class.
fillable: The fillable property is an array defined in the model that specifies which attributes are
allowed to be mass assigned.
39
Only the attributes specified in the fillable array will be mass assigned, and any other attributes
will be ignored.
This is a security feature that helps protect against unwanted mass assignment.
• protected $guarded = ['id']; => the field name inside the array is not mass assignable
guarded: The guarded property is the inverse of the fillable property, instead of specifying the
attributes that can be mass-assigned? you define the attributes that are not allowed to be
mass-assigned.
If a model is using the guarded property, all attributes will be protected by default.in this ex we
guard only one specific field and allowing the rest to be Mass assignable.
• protected $guarded = [‘*’]; ==> If you want to block all fields from being mass-assigned
you can just do this.
hidden: The hidden property is an array that contains a list of attributes that should be hidden.
This is useful when you want to exclude sensitive information from being exposed.
--------------------------------
Mass Assignment:
• Mass means large number
• Assignment means the assignment operator in programming
Eloquent ORM offers Mass Assignment functionality which helps insert large number of inputs
to database.
Life, without Mass Assignment 😩
Let's consider that there is a form with 10 fields of user information.
40
and our Controller's store method looks like:
We are assigning each input manually to our model and then saving it to database.
Life, with Mass Assignment 🥳
Laravel Eloquent ORM provides a create method which helps you save all the input with single
line. Input fields name attribute must match the column name in our database.
41
security problems
let's consider that we have an is_admin column on users table with true / false value. A
malicious user can inject their own HTML, a hidden input as below
With Mass Assignment, is_admin will be assigned true and the user will have Admin rights on
website, which we don't want 😡
Avoiding the security problems
Any input field other than these passed to create() method will throw
MassAssignmentException.
-------------------------------------
2) We can specify (blacklist) which columns cannot be mass assigned. You can achieve this by
adding $guarded property in model class:
------------------------------------------------------------------------------------------------------------------------------
model? I have a table with 56 fields, and just 3 out of those fields need to be protected. using
fillable in this situation, you may, but if you want an easier way to secure it from mass-
43
32) What is Eloquent in Laravel?
In Laravel, Eloquent is the default Object-Relational Mapping (ORM) system provided by the
framework. It simplifies database operations by allowing you to work with database records
and relationships.
Model-Database Mapping: Eloquent allows you to define model classes that represent
database tables. Each instance of a model class represents a row in a table. You can define
relationships between models, such as one-to-one, one-to-many, or many-to-many.
Query Builder: that allows you to construct database queries. You can use methods such as
where, orderBy, groupby, and join to build complex queries without writing raw SQL.
CRUD Operations: Eloquent simplifies the process of performing CRUD (Create, Retrieve,
Update, Delete) operations on database records. You can create new records using the create
method, retrieve records using find, all, or where method, update records using update or save
methods, and delete records using the delete method.
44
First, define the relationship between the User and Post models. In the User model, you would
define a hasMany relationship to represent the user's posts.
In the Post model, define a belongsTo relationship to represent the post's owner (user)
to retrieve all users along with their posts, you can use eager loading in your controller
45
Now, you can access the user's posts using the relationship property.
For example,
assuming you have a user with an ID of 1, you can retrieve their posts as follows:
In this example,
Laravel will perform a lazy load and fetch all the related posts from the database for that user.
------------------------------------------------------------------------------------------------------------------------------
In this example,
The published query scope defines a constraint that selects articles where the is_published
column is set to true.
46
In this example,
The published query scope is applied to the Article model, and the get method retrieves all the
published articles.
You can also use the query scope within a query builder instance, like this:
In this case, the published query scope is chained with additional query builder methods to
refine the query.
------------------------------------------------------------------------------------------------------------------------------
34) Migrations?
Migrations are used to create database schemas in Laravel in migration files
• Run => php artisan make:migration create_example_table: This will generate a new
migration file in the `database/migrations` directory with a name like
`20231101000000_create_example_table.php`. The timestamp in the filename ensures
the order of execution if you have multiple migrations.
• Run => php artisan migrate: The up() method in migration file runs and laravel will
execute the migration and create the "examples" table in your database.
• Run => php artisan migrate:rollback: The down() method in migration file runs, and we
will roll back the previously run migration.
47
------------------------------------------------------------------------------------------------------------------------------
35) Seeders?
Seeders are classes that allow you to populate the database with initial data for testing. By
using seeders, you can quickly and easily create a set of data that can be used across multiple
environments (Local, Production).
Run the php artisan make:seeder UsersTableSeeder Artisan command for Ex, this command
generates a new seeder class in the database/seeders directory. Inside the seeder class, you
define the data
48
In this example, we are inserting two user records into the users table with their names, emails,
and hashed passwords.
Run => php artisan db:seed --class=UsersTableSeeder
This will execute the run() method in the UsersTableSeeder class and insert the data into the
users table.
You can also run all the seeders at once by => php artisan db:seed
But you must call UsersTableSeeder in DatabaseSeeder class.
------------------------------------------------------------------------------------------------------------------------------
36) Factories?
Laravel provides a feature called "factories" that allows you to generate dynamic and randomized
data.
For example, to create a factory for the User model, run the following command:
php artisan make:factory UserFactory --model=User
This will generate a UserFactory class in the database/factories directory.
49
In this example,
We use the faker property provided by the factory to generate a random name and a unique
email for each user. The bcrypt() function is used to hash the password.
To populate the users table with the defined data, you can use the db:seed Artisan command.
php artisan make:seeder UserSeeder
This will execute the run() method in the UserSeeder class and insert the data into the users table.
----------------------------------------------------------------------------------------------------------------------------
50
later if needed. It is useful when you want to save historical data or implement a "trash"
functionality in your application.
To enable soft delete in Laravel, you need to perform the following steps:
Step 1: Add a nullable deleted_at Column of type datetime in your database table, this column
will be used to store the soft delete timestamp for each record.
By using the SoftDeletes trait and specifying the deleted_at column in the $dates property,
Laravel will automatically handle the soft delete functionality for the User model.
51
Step 4: Retrieving Soft Deleted Records
If you need to retrieve soft deleted records, you can use the withTrashed() method.
$users = User::withTrashed()->get();
This query will retrieve both non-deleted and soft deleted records.
Step 5: To restore a soft deleted record, you can use the restore() method.
$user = User::withTrashed()->find(1);
$user->restore();
This will remove the soft delete from the record, making it available in regular queries again.
To permanently delete a soft deleted record, you can use the forceDelete() method.
$user = User::withTrashed()->find(1);
$user->forceDelete();
This will remove the record from the database permanently.
------------------------------------------------------------------------------------------------------------------------------
Session:
A session in Laravel is a server-side mechanism for storing user-specific data across multiple
requests.
52
In this example, the /store-session route stores data in the session using the put() method of
the session object ($request->session()).
The /get-session route retrieves the stored data using the get() method.
The /forget-session route removes the stored data using the forget() method.
The session data is stored on the server-side and associated with the client using a session ID.
Cookie:
A cookie in Laravel is data sent from the server and stored on the client's browser.
It allows you to store data that persists across different sessions or even different visits to your
application.
Cookies are stored on the client-side as text files and are sent back to the server with each
subsequent request to identify the client and retrieve any stored cookie data.
Laravel provides a cookie helper for creating and manipulating cookies.
You can set a cookie using the cookie() function, and retrieve cookie values using the request()
->cookie() method.
53
Cookies are commonly used to store non-sensitive data, such as user preferences, language
settings, or tracking information. They can also be used for implementing features like
"Remember me" functionality.
------------------------------------------------------------------------------------------------------------------------------
39)What is Tinker?
In Laravel, Tinker is a REPL (Read-Eval-Print Loop) tool that allows you to interact with your
application's code and perform tasks directly from the command line.
It provides an interactive shell where you can execute PHP code and interact with your Laravel
application's models, database, and other components.
54
Here's a simple example to illustrate the use of a REPL (Tinker) in Laravel:
------------------------------------------------------------------------------------
40)How do you check the installed Laravel version of a project?
Using the command PHP Artisan --version or PHP Artisan -v
----------------------------------------------------------------------------------------------
41)What is pagination?
Pagination in Laravel allows you to divide a large set of results into smaller, more manageable
sections called "pages." This helps
improve the user experience (UX) by displaying only a limited number of results per page.
reducing the load time.
Laravel provides built-in pagination functionality that you can easily use in your application.
Here's an example of how to use pagination in Laravel:
Retrieve paginated results from the database:
55
Display paginated results in a view: In your users.index view, you can display the paginated
results using Laravel's links() method, which generates the pagination links.
------------------------------------------------------------------------------------------------------------------------------
In the example,
There are 10 data in your users table and you want to skip the 4 start data and get the
remaining 6 data. Then use the skip and take query in laravel for it. Alternatively, you may use
the limit and offset methods.
56
Namespaces provide a way to avoid naming conflicts and make it easier to organize and
manage code in large applications.
By default,
Laravel uses the PSR-4? autoloading standard, which maps namespaces to directory structures
and helps PHP and Laravel locate the class when it is called.
For example,
let's say you have a class called UserController in your Laravel application.
You can place this class in a directory called App\Http\Controllers and define its namespace as
namespace App\Http\Controllers;.
In this example,
the UserController class is declared with the namespace App\Http\Controllers. The use
statement is also used to import the Controller class from the same namespace.
------------------------------------------------------------------------------------------------------------------------------
Laravel follows the PSR-4, making it easy to autoload classes without the need for manual
require statements.
This allows PHP to automatically load the required class files when they are referenced in the
code.
Here's an example to illustrate how PSR-4 autoloading works in Laravel:
• Directory structure:
Assume you have a Laravel application with the following directory structure:
57
• Namespace declaration:
Inside the UserController.php file, you declare the namespace and class:
Here,
the "App\\": "app/" mapping indicates that the App namespace corresponds to the app/
directory.
• Running Composer:
After making changes to the composer.json file, you need to run the composer dump-
autoload command in your terminal. This regenerates the autoloader file based on the
PSR-4 autoloading configuration.
• Autoloading in action:
With the PSR-4 autoloading configuration you can simply reference the UserController
class in your code without requiring it manually.
58
----------------------------------------------------------------------------------------------------------------------------- -------------
----------------------------------------------------------------------------------------------------------------------------- -------------
46)What is the use of dd() function?
The dd() function in Laravel is a debugging tool used to "dump and die" because it dumps the
given variable and ends the script execution, preventing any further code from running.
The dd() function is commonly used during development to quickly inspect the contents of
variables, arrays, objects, or any other data structure.
In this example,
we have an array representing a user. By using the dd() function, we can inspect the contents of
the $user variable.
The output:
Additionally,
59
You can pass multiple arguments to the dd() function, allowing you to inspect multiple variables
or data structures at once:
----------------------------------------------------------------------------------------------------------------------------- -------------
In this example, the Route::get() method is used to define a route for the /hello URI. As the
second argument, a closure (anonymous function) is provided.
The closure doesn't have a function name, but it can contain any valid PHP code.
In this case, When the /hello route is accessed, Laravel will execute the closure and return the
specified response.
Closures can also accept parameters:
60
In this example, the closure accepts a parameter named $id. Inside the closure, it retrieves a
user from the database based on the provided $id and returns a customized greeting message
using the user's name.
----------------------------------------------------------------------------------------------------------------------------- -------------
• One to One
• One to Many
• Many to Many
• Has One Through
• Has Many Through
• One to One (Polymorphic)
• One to Many (Polymorphic)
• Many to Many (Polymorphic)
Polymorphic Relationships
A polymorphic relationship allows the child model to belong to more than one type of model
using a single association. For example, imagine you are building an application that allows
users to share blog posts and videos. In such an application, a Comment model might belong to
both the Post and Video models.
1)One to One:
In this relationship, each record in one database table is associated with one record in another
table. For example, a User model have a one-to-one relationship with a Profile model, where
each user has one profile
61
62
2)One to Many:
In this relationship, a single record in one table can be associated with multiple records in
another table. For example, a User model may have a one-to-many relationship with a Post
model, where a user can have multiple posts.
63
3) Many to Many:
multiple records in one table can be associated with multiple records in another table. This
relationship requires an intermediate table, referred to as a pivot table, to store the
associations. For example, a User model have a many-to-many relationship with a Role model,
where a user can have multiple roles and a role can belong to multiple users.
64
4)Has One Through:
This relationship allows you to access a model indirectly. For example, A User model can have
one Profile, and a Profile belongs to one Country. We'll use the "Has One Through" relationship
between the User and Country models through the Profile model.
65
66
5)Has Many Through:
This relationship allows you to define a relationship that accesses distant relations via an
intermediate relation. It is like a "has many" relationship but allows you to access multiple
models indirectly. For example, A Country model can have many Region, and a Region can have
many City. We'll use the " has-many-through " relationship, where a Country has many cities
through a Region model.
67
Note the imageable_id and imageable_type columns on the images table. The imageable_id
column will contain the ID value of the post or user, while the imageable_type column will
contain the class name of the parent model, is used by Eloquent to determine which "type" of
parent model to return when accessing the imageable relation. In this case, the column would
contain either App\Models\Post or App\Models\User.
68
7)One to Many (Polymorphic):
A one-to-many polymorphic relation is similar to a typical one-to-many relation; however, the
child model can belong to more than one type of model using a single association. For example,
imagine users of your application can "comment" on posts and videos. Using polymorphic
relationships, you may use a single comments table to contain comments for both posts and
videos. First, let's examine the table structure required to build this relationship:
69
70
8)Many to Many (Polymorphic):
For example, a Post model and Video model could share a polymorphic relation to a Tag model.
Using a many-to-many polymorphic relation in this situation would allow your application to
have a single table of unique tags that may be associated with posts or videos. First, let's
examine the table structure required to build this relationship:
The Post and Video models will both contain a tags method that calls the morphToMany
method provided by the base Eloquent model class.
71
72
49)Explain MVC Architecture
MVC stands for Model View Controller.
It segregates business and logic from the user interface. This is achieved by separating the
application into three parts:
------------------------------------------------------------------------------------------------------------------------------
In Laravel, you can implement throttling using the built-in middleware called "throttle". This
middleware allows you to define rate limits based on the number of requests per minute.
Now, you can apply the throttle middleware to your routes or route groups. Here's an example
of how to use it:
73
In this example, the 'throttle' middleware is applied to a group of routes. The rate_limit
parameter specifies the number of requests allowed per minute. In this case, it allows 1 request
per minute. You can adjust the rate_limit value according to your requirements.
By implementing the throttle middleware, Laravel will automatically handle the throttling for
you. If a user exceeds the specified rate limit, Laravel will return a 429 "Too Many Requests"
response.
------------------------------------------------------------------------------------------------------------------------------
51)What is modular?
Laravel is an amazing framework but when it comes to building a complex project the default
Laravel structure becomes cumbersome.
If you have worked on a large project before, you might have noticed that the logic in your
controller becomes much, you might spend a lot of time looking for things because everything
is bunched together.
This is what the modular approach is trying to resolve, building each part of the project on its
own but communicating with other modules in the project, every module has its own
model,view,controller,route meaning every module has a group of classes that are related.
In this structure,
• The app folder is the root of the application. Inside the app folder, there is a
• Each module folder typically contains directories for Controllers, Models, Views, Routes,
and other related files, specific to that module. For example, the Blog module has
74
• The Http folder contains general controllers and middleware that are not specific to any
module. The Models folder holds the application's shared models, and the Views folder
• The config folder stores configuration files for the Laravel application, and the database
• The resources folder contains assets like CSS, JavaScript, and language files. The routes
folder holds the route definitions for the application, including routes specific to each
module.
• Class: A class is a fundamental concept in OOP. It is a template that defines the structure
and behavior of objects. A class encapsulates data and the methods. It serves as a
building block for creating objects which are instances of the class.
for example, ==> in PHP you can define a class called "Car" with properties like "color"
and "brand" and methods like "method1()". You can then create multiple instances of
the "Car" class to represent different cars with different colors and brands
------------------------------------------------------------------------------------------------------------------------------
75
53)Request Lifecycle?
• First Step(index.php)
• (HTTP / Console) Kernels
• Service Providers
• Routing
• Controller
• View
-----------------------
• First Step:
The entry point for all requests to a Laravel application is the public/index.php file. This file
doesn't contain much code, it is a starting point for loading the rest of the framework.
The index.php file Check If the Application is under maintenance. If not, Register the Auto
Loader => Composer provides a convenient, automatically generated class loader for this
application.
Then retrieves an instance of the Laravel application from bootstrap/app.php.
Next, the incoming request is sent to either the HTTP kernel or the console kernel, depending
on the type of request that is entering the application.
For now, let's just focus on the HTTP kernel, which is in app/Http/Kernel.php.
76
2) defines a list of HTTP middleware that all requests must pass through before being
handled by the application.
Think of the kernel as being a big black box that represents your entire application. Feed it HTTP
requests and it will return HTTP responses.
Service providers are responsible for bootstrapping framework's components, such as the
database, queue, validation, and routing components. All service providers for the application
are configured in the config/app.php configuration file's providers array.
Laravel will iterate through this list of providers and instantiate each of them. After
instantiating the providers, the register method will be called on all the providers. Then, the
boot method will be called on all the providers.
• Routing
One of the most important service providers in your application is the
App\Providers\RouteServiceProvider.
This service provider loads the route files in your application's routes directory. open the
RouteServiceProvider code and look at how it works!
The Request will be handed off to the router. The router will dispatch the request to a route.
Middleware provides a convenient mechanism for filtering HTTP requests entering your
application.
For example,
Laravel includes a middleware that verifies if the user of your application is authenticated. If the
user is not authenticated, the middleware will redirect the user to the login screen. However, if
77
the user is authenticated, the middleware will allow the request to proceed into the
application.
The route or controller method will be executed, and the response returned by the route or
controller method to view or as Json.
------------------------------------------------------------------------------------------------------------------------------
54)Explain the function of Console Kernel
In Laravel, the Console Kernel is responsible for defining the available commands and
scheduling tasks that can be run from the command line interface (CLI).
It acts as the entry point for console-based interactions with your Laravel application.
78
Open the app/Console/Kernel.php file:
This Kernel class extends the Illuminate\Foundation\Console\Kernel base class.
The GreetCommand should be a custom command class that you define in the
app/Console/Commands directory.
-------------------------------
In this example,
the greet:all command is scheduled to run daily at 8 AM.
This will execute the code defined within the handle method of the GreetCommand class.
• database service
• mail service
• cache service
• session service
These services are readily available and can be accessed and utilized within your application
without requiring additional configuration or setup.
Service Container:
The service container is a powerful tool for managing class dependencies and performing
dependency injection automatically in your application.
Here's a simplified example to demonstrate the difference between using a service container in
Laravel and manual dependency injection in regular PHP.
Laravel Service Container Example:
80
In this example, we have a UserController that depends on a UserService. By type-hinting the
UserService in the constructor, Laravel's service container automatically resolves the
dependency and provides an instance of UserService.
This allows us to use $this->userService within the register method without manually
instantiating UserService.
81
In this example, we manually create an instance of UserService and inject it into the constructor
of UserController.
The dependency is resolved explicitly in php without the use of a service container.
Whenever we need to create a new instance of UserController, we must remember to manually
create and inject the UserService instance.
In the Laravel example, the service container automatically resolves the dependencies when
creating an instance of the UserController.
This reduces the manual effort required to instantiate and inject dependencies.
In the regular PHP example, dependencies must be manually created and injected.
82
What do we mean by "bootstrapped"?
In general, we mean registering things, including registering service container bindings, event
listeners, middleware, and even routes.
Service providers are the central place to configure your application.
If you open the config/app.php file included with Laravel, you will see a providers array.
These are all the service provider classes that will be loaded for your application.
By default, a set of Laravel core service providers are listed in this array. These providers
bootstrap the core Laravel components, such as the mailer, queue, cache, and others. Many of
these providers are "deferred" providers, meaning they will not be loaded on every request,
but only when the services they provide are actually needed.
is a class that acts as a bridge between your application and the Laravel service container. It
defines how services should be registered and made available to the container. Service
providers are typically used to bootstrap and configureservices of your application, such as
registering routes, database connections, event listeners, and more.
You may need to bind your package's services into the container.
• Binding
You can bind a service (or a class) to the container. This means whenever you resolve
this service, the container will give you the instance of the class.
• Singleton Binding
Singletons are used when you want to ensure that a class is only instantiated once
throughout the lifecycle of an application.
83
• Instance Binding
You can bind an existing instance into the container. When the container is later asked
to resolve this binding, it will return the already created instance.
• Binding Primitives
Sometimes you may have two classes that depend on a common primitive value (like a
string). You can use context-based binding to resolve this.
• Resolving
You can resolve services out of the container either by their binding name or through
type-hinting in a method or constructor.
• Tagging
You can tag related bindings, making it easier to resolve them all at once.
84
• Service Providers
Service providers are a way to group related IoC registrations in a single location. They
provide a bootstrapping mechanism for the framework and your application.
• Automatic Injection
Laravel's IoC container can automatically resolve and inject dependencies for you.
• Method Injection
Not only can you inject services into constructors, but you can also type-hint
dependencies on controller methods.
----------------------------------------------
85
Let's walk through an example that demonstrates the usage of the service container and service
provider to bind and resolve a service.
86
Using the Service:
Now, you can use the service anywhere in your application by resolving it from the service
container.
For example,
Let's create a route that uses the service. In your routes/web.php file,
------------------------------------------------------------------------------------------------------------------------------
The register method in the Service Provider class is used to bind classes or services to the
Service Container. It should not be used to access any other functionality or classes from the
application as the service you are accessing may not have loaded yet into the container.
The boot method runs after all the dependencies have been included in the container and we
can access any functionality in the boot method. Like you can create routes, create a view
composer, etc. in the boot method.
------------------------------------------------------------------------------------------------------------------------------
In this example, the Route facade provides a static interface to the Illuminate\Support\
facades\Route class.
It allows you to define routes without explicitly creating an instance of the router.
The Auth facade gives you access to Laravel's authentication services, such as checking if a user
is authenticated, retrieving the authenticated user, and more.
• The DB facade:
The DB facade provides a static interface to Laravel's database query builder. It allows you to
perform database operations without explicitly creating a query builder instance.
88
The Session facade allows you to work with session data. You can store values in the session,
retrieve them, and perform other session-related operations.
This feature is especially useful when you want to add methods to Laravel's core classes or
third-party packages without modifying their source code.
In this example,
We're extending the Str class, which is provided by Laravel for string manipulation.
We use the macro() method to define a new method called 'reverse'.
The 'reverse' method takes a string as input and calls the strrev() PHP function to reverse the
string.
Once the macro is defined, you can use the 'reverse' method on any string in your application,
just like any other method provided by the Str class.
89
----------------------------------------------------------------------------------------------------------------------------- -------------
They're used to provide a simple way to access complex objects and methods, and they're often
used to centralize the configuration of those objects.
Facades can be mocked in Laravel using the shouldRecieve method, which returns an instance
of a facade mock.
$value = Cache::get('key');
Cache::shouldReceive('get')->once()->with('key')->andReturn('value');
----------------------------------------------------------------------------------------------------------------------------- -------------
90
You can also log data along with your messages. For example,
the following code logs an info message with the current user's ID:
• Debug problems in your application: When you're trying to debug a problem with your
application, you can use logging to track what's happening. For example, you can log
when a certain route is accessed, when a specific function is called, or when a database
query is executed. This can help you to narrow down the source of the problem.
• Tracking activity: Logging can also be used to track activity in your application. This can
be helpful for understanding how users are using your application
Log::info('The user with ID {id} accessed the post with ID {post_id}.', ['id' => Auth::user()-
>id, 'post_id' => $post->id]);
91
log channels:
log channels provide a way to specify how log messages are handled and where they are
stored. By default, Laravel uses the "stack" channel, which allows you to configure multiple
channels and specify their behavior. Let's explore the difference between log channels with an
example.
Here's an example configuration in the config/logging.php file:
In this example, the 'stack' channel is used as the default channel. It is configured to use two
other channels: 'single' and 'daily'.
The 'single' channel logs messages to a single file (laravel.log),
while the 'daily' channel logs messages to a file per day (daily.log).
92
To log messages using a specific channel, you can use the Laravel logging facade's methods,
such as Log::channel() or Log::stack(). Here's an example:
In the same configuration file, within the 'connections' array, add the 'logging' key to the
desired database connection. Set its value to true to enable query logging for that connection.
Here's an example of (config/database.php) file:
93
After these changes, Laravel will start logging all the database queries executed.
To access the logged queries, you can use the DB::getQueryLog() method. This returns an array
containing all the executed queries.
94
Clearing View Cache:
The view cache stores compiled views for faster rendering.
To clear it, you can use the view:clear Artisan command:
1) Define an Event:
96
In this case, we fire the OrderShipped event and pass the shipped order as a parameter.
When the OrderShipped event is fired, Laravel's event will locate the registered listeners and
execute their handle() methods. In this example,
the SendShipmentNotification listener's handle() method will be called with the OrderShipped
event instance, allowing you to perform any necessary actions, such as sending a shipment
notification.
By default, Laravel uses the "gettext" translation library, which utilizes language files and a
translation helper function (__() or trans()) to handle translations.
Language files are stored in the resources/lang directory and organized by language and file
format (en, fr, es).
Each language file contains an array where the keys represent the original strings and the
values represent their translations.
97
• Use the __() helper function to retrieve translations in your views or controllers:
• In this example, we have language files for English and French that contain translations
for the welcome and greeting keys.
• The second argument of the helper function allows you to pass dynamic values to the
translation, like the name in the greeting translation.
------------------------------------------------------------------------------------------------------------------------------
65)What are collections?
• Collections are a feature that provides a convenient way to manipulate arrays of data,
allowing you to perform operations on arrays, such as filtering(), mapping(), sorting(),
reduce(), groupBy(), sum() and more.
• They are widely used in Laravel for working with database query results and API
responses.
Here's an example to demonstrate the usage of collections in Laravel:
98
In this example,
• we start by creating a collection from the $users array using the collect() helper
function.
• use the where() method to filter users older than 25.
• The pluck() method is used to extract the names of the filtered users.
• We sort the names in descending order using the sortDesc() method.
• Finally, we iterate over the sorted names and output them
------------------------------------------------------------------------------------------------------------------------------
100
------------------------------------------------------------------------------------------------------------------------------
67)What are queues in Laravel?
• In Laravel, queues are a feature that allows you to defer time-consuming tasks for
background processing.
• Instead of executing these tasks within the request-response cycle, you can push them
to a queue where they are processed by a queueing system.
• Queues are particularly useful for tasks like sending emails, processing large data sets,
generating reports, and performing other tasks that can be handled outside the
immediate response cycle.
• By using queues, you can improve the performance and responsiveness of your
application.
Here's an example to demonstrate the usage of queues in Laravel:
1) Define a job class that encapsulates the task you want to queue.
For example, create a ProcessOrderJob class in app/Jobs directory:
101
2) Dispatch the job to the queue from your controller or wherever the task needs to be
triggered:
In this example,
• we define a ProcessOrderJob class that implements the ShouldQueue interface.
102
• The job class contains a handle() method that defines the task to be performed when
the job is processed.
• In this case, it could be sending a confirmation email or updating the database based on
the order details.
• The Laravel queue started with the queue:work command, it retrieves the jobs from the
queue and executes their handle() method.
------------------------------------------------------------------------------------------------------------------------------
Accessors and mutators are methods used to manipulate the attributes of an Eloquent model.
They allow you to define custom getters and setters for model attributes, providing a way to
format the attribute values when retrieving or saving them.
• Accessors:
An accessor is a method that is used to retrieve the value of an attribute.
It is defined using the get{AttributeName}Attribute naming convention.
In this example,
103
• The getNameAttribute accessor is defined for the "name" attribute.
• It modifies the value of the "name" attribute by capitalizing the first letter using the
ucfirst function.
• When you access the "name" attribute on a User model instance, Laravel will
automatically call this accessor and return the modified value.
-------------------------------------
• Mutators:
A mutator is a method that is used to set the value of an attribute.
It is defined using the set{AttributeName}Attribute naming convention.
In this example,
69)Broadcasting?
• Introduction
104
In Laravel, Broadcasting is a feature that allows you to broadcast real-time events to your
application's frontend using a supported broadcasting driver (e.g., WebSocket, Redis, Pusher).
It provides a convenient way to build real-time features such as chat applications, notifications,
live updates, and more.
Broadcasting can be useful in scenarios where you need to push updates to multiple clients
without refreshing the page manually.
• Server-Side Installation
Laravel supports multiple broadcasting drivers, including Pusher, Redis, log, and more. Select
the driver you want to use and install any required dependencies.
Configure the Broadcasting Driver:
Update the BROADCAST_DRIVER value in your .env file to match the chosen broadcasting
driver. Additionally, configure the driver-specific settings in the config/broadcasting.php file.
Define Events:
Create event classes that represent the events you want to broadcast. These classes should
implement the ShouldBroadcast interface and define the broadcastOn() method to specify the
channel or channels to broadcast on.
• Client-Side Installation
------------------------------------------------------------------------------------------------------------------------------
70)Task Scheduling?
• Task Scheduling in Laravel allows you to automate the execution of tasks at specified
intervals. It provides a convenient way to schedule tasks such as database cleanups,
sending notifications, and more.
• Laravel's task scheduling is built on top of the cron scheduling system available in Unix-
like operating systems.
Here are the steps to set up and use Task Scheduling in Laravel:
106
Once you have defined your task, you need to register it in the schedule method. You can use
the ->command () method to register an Artisan command or used the protected $commands
property.
107
• Remember to run php artisan schedule:run manually or set up the cron job to execute
the scheduled tasks.
------------------------------------------------------------------------------------------------
It provides a consistent interface to authenticate users with different social media providers
and retrieve user details.
Here's a simple example of using Socialite to authenticate a user with a social media provider,
in this case, GitHub:
Install Socialite:
108
Usage in Views:
Create a button or link in your view to initiate the authentication process:
Clicking on this link will redirect the user to GitHub's authorization page, where they can grant
permission to your application.
------------------------------------------------------------------------------------------------------------------------------
72)What is Sitemap in Laravel?
A sitemap.xml is a file used by websites to provide search engines with information about the
pages on their site.
It serves as a directory of all the available pages and their corresponding metadata, allowing
search engines to navigate and index the website more effectively.
Search engine indexing: Sitemaps help search engines understand the structure of your website
and index its pages.
Priority and frequency information: Sitemaps allow you to indicate the relative importance of
different pages on your site using priority values.
109
Supporting rich snippets and enhanced search results: Sitemaps can include additional
metadata for each URL, such as last modification date, language, and specific content types
(e.g., video, images).
----------------------------
To build a sitemap using the Spatie Sitemap package in a Laravel application, follow these steps:
2) Open your config/app.php file and add the following line to the 'providers' array:
In this example,
the generate() method creates a new Sitemap instance and adds URLs using the add() method.
Each URL is created with the Url class, which allows you to set priority and change frequency as
desired.
Define a route in your routes/web.php file to point to the generate() method of the
SitemapController:
110
Finally, you can access the sitemap.xml file by visiting this link.
------------------------------------------------------------------------------------------------------------------------------
It allows you to simulate the external dependencies, like databases, APIs, or third-party
libraries, this isolates your test from real-world interactions.
• Prophecy:
Another popular mocking library is a third-party package often used as an alternative to
Mockery. It's known for its clear syntax and ease of use.
Example with Mockery, Let's say you have a class UserService that uses the Auth facade to
check if a user is authenticated.
To mock the Auth::check() and Auth::user() methods, you can use the shouldReceive() method
provided by the Mockery library in a test class.
111
In this example,
• We use the Mockery library to mock the Auth facade and create a mock object for the
facade.
• We then use the shouldReceive() method on the mock object to define the expected
behavior. In this case, we mock the check() method to always return true.
• After mocking the facade, we create an instance of the UserService class and call its
isAdmin() method.
------------------------------------------------------------------------------------------------------------------------------
112
2) Create a repository class that implements the interface:
Next, this class will provide the actual implementation for the data access methods defined in
the interface.
In this example,
113
We have implemented the UserRepository class that implements the UserRepositoryInterface.
The repository class uses the User model to perform the actual database operations for
retrieving, creating, updating, and deleting users.
To facilitate dependency injection and allow the application to resolve the repository interface
to its corresponding concrete implementation, you need to bind the repository interface to the
repository class in Laravel's service container. This can be done in the AppServiceProvider or
any other service provider class.
Now, you can use the repository in your application's services or controllers by injecting it
through constructor injection or method injection.
114
In this example,
The UserService is injected with the UserRepositoryInterface.
The service can then utilize the repository methods to fetch and manipulate user data without
directly accessing the database layer.
------------------------------------------------------------------------------------
75)What is the Singleton design pattern in laravel?
The Singleton design pattern is not specific to the framework itself but is a general design
pattern that can be used in any application, including Laravel.
The Singleton pattern ensures that only one instance of a class can be created and provides a
global point of access to that instance throughout the application.
115
In this example,
the SingletonClass has a private constructor to prevent direct instantiation. The getInstance()
method is used to create or retrieve a single instance of the class. It checks if an instance
already exists and creates one, if not, the doSomething() method represents some actions that
can be performed by the singleton instance.
This will provide you with the single instance of the class. You can then call any methods or
perform actions in that instance.
The Singleton design pattern offers several benefits when it comes to managing memory and
resource usage in an application:
116
Single instance:
The Singleton pattern ensures that only one instance of a class exists throughout the
application.
This means that resources associated with that instance, such as memory, are allocated only
once. It prevents unnecessary duplication of objects and reduces memory usage.
Global access:
The Singleton provides a global point of access to the single instance. This eliminates the need
to pass instances between different parts of the application.
Resource management: The Singleton pattern can be used to manage limited resources
efficiently. For example,
If you have a class managing a connection to a database, the Singleton pattern ensures that
only one instance of that class exists, preventing multiple connections.
----------------------------------------------------------------------------------------------------------------------------
76)What php laravel observer design pattern?
The Observer design pattern in Laravel allows you to define a one-to-many dependency
between objects, so that when one object changes, all its dependents are automatically notified
and updated.
In Laravel, the Observer pattern is commonly used with the Eloquent ORM to listen for specific
events that occur on a model, such as creating, updating, or deleting records.
Here's a simple example to illustrate the usage of the Observer pattern in Laravel:
This command will generate a model file (User.php) in the app/Models directory.
117
In this example, we have a basic User model with the name, email, and password attributes.
Create an Observer:
Create a new observer using the Artisan command-line tool. For example, to create a
UserObserver.
In this example,
We have defined event listener methods for the created, updated, and deleted events on the
User model. These methods will be automatically triggered when corresponding events occur.
118
Register the Observer:
To make Laravel aware of the observer, you need to register it.
Open the AppServiceProvider class (app/Providers/AppServiceProvider.php) and inside the
boot method, add the following code:
This code registers the UserObserver to observe changes on the User model.
Now, whenever a new user is created, updated, or deleted, the corresponding event listener
methods in the UserObserver will be automatically called.
----------------------------------------------------------------------------------------------------------------------------
77)How can we reduce memory usage in Laravel?
Reducing memory usage in Laravel can help optimize the performance of your application.
Here are a few simple examples of how you can reduce memory usage in Laravel:
119
Paginate Large Result Sets:
When fetching large results from the database, it's advisable to paginate the data instead of
retrieving everything at once.
This will retrieve 10 users at a time, and you can navigate through the paginated results using
the provided pagination links.
----------------------------------------------------------------------------------------------------------------------------
78)What is a lumen?
Designed for building microservices and APIs. It's lightweight and prioritizes speed and
performance.
Lacks many features compared to Laravel, such as authentication, session management, and
routing helpers.
120
----------------------------------------------------------------------------------------------------------------------------- -------------
1) Features:
Resource-based: Define resources that correspond to your Eloquent models, granting CRUD
(Create, Read, Update, Delete) functionality.
Customization: Customize resource fields, filters, cards, and actions to the admin panel.
Actions: Perform custom actions on one or more resources, such as generating reports, sending
emails, or triggering other processes.
Security: Implement user roles and permissions to control access to different parts of the admin
panel.
Scalability: Designed to handle large datasets and applications with high traffic.
2) Benefits:
121
Integration: Integrates with other Laravel libraries and packages.
------------------------------------------------------------------------------------------------------------------------------
80)What is the use of Bundles in Laravel?
Bundles (Not commonly used in Laravel):
In some older versions of Laravel, the term "bundle" was used to refer to a collection of related
code, assets, and resources bundled together as a package.
Bundles were a way to organize and distribute components in Laravel applications.
However, in more recent versions of Laravel, the concept of bundles has been replaced by
packages and modules.
------------------------------------------------------------------------------------------------------------------------------
81)Debug mode?
The debug option in your config/app.php configuration file determines how much information
about an error is displayed to the user.
In your production environment, this value should always be false. If the APP_DEBUG variable is
true in production, you risk exposing sensitive configuration values to your application's end
users.
------------------------------------------------------------------------------------------------------------------------------
Laravel Forge
Laravel Forge is a server management and application deployment service designed to make
launching and maintaining your Laravel applications easier. It's not officially part of the Laravel
framework itself, but it's highly compatible and popular among Laravel developers.
Laravel Vapor
Vapor is a serverless deployment platform specifically designed for Laravel applications. It is a
product offered by Laravel's creator, Taylor Otwell, and his team. Vapor allows you to deploy
your Laravel applications to serverless environments, such as AWS Lambda, with ease.
122
123