Lara Readmd
Lara Readmd
Questions
(https://devinterview.io/questions/web-and-mobile-development/)
You can also find all 100 answers here Devinterview.io - Laravel
(https://devinterview.io/questions/web-and-mobile-development/laravel-interview-
questions)
Key Features
Modular Packaging System: Composant provides an organized venue for managing all third-party packages.
Eloquent ORM: Offers an intuitive and PHP-analogous way to perform database operations.
Database Migrations, Seeding, and Query Builder: Simplifies database tasks, including seamless transition
across multiple environments.
Artisan Command-Line Utility: Facilitates a range of tasks, from building controllers to managing databases.
Middleware: Offers a flexible mechanism for HTTP request filtering.
Task Scheduling: Allows the application to automate long-running tasks.
I/O Concurrent Downloads: Speeds up downloads using PHP's multi-curl functions.
Robust Background Job Processing; using Queues.
Realtime Event Broadcasting.
Unit and Work Testing: Inbuilt tools for quality assurance.
Logging and Integrated Testing Tools: Ensures robustness and stability.
Blade Templating Engine: A clean, straightforward syntax for designing the application's views.
RESTful Resource Controllers: Conforms to the REST architectural style.
In-depth Documentation: Comprehensive and easy to follow.
MVC Overview
Model: Represents the data and the business rules concerning the data. This includes data persistence,
validation, business logic, and authentication.
View: Presents data to the user in a specific format. The view receives data from the model and user interactions
from the controller.
Controller: Acts as an intermediary between models and views. It processes user input, interacts with the model,
and selects the view to display.
View: Blade, Laravel's templating engine, is responsible for the visual representation of data. Blade templates are
versatile and enable dynamic content rendering.
Controller: Laravel utilizes controllers to orchestrate data flow between models and views. Controllers handle
user requests, validate input, perform application logic, and determine the appropriate view to render.
namespace App;
use Illuminate\Database\Eloquent\Model;
2. View: a Blade template that conditionally renders a greeting based on whether a user is authenticated or not.
@if (Auth::check())
<p>Hello, {{ Auth::user()->name }}!</p>
@else
<p>Welcome, guest!</p>
@endif
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
Core Requirements
1. PHP: A server with PHP 7.4 or higher is essential.
2. Extensions: Install OpenSSL, PDO, Mbstring, Tokenizer, and XML PHP extensions.
Storage Setup
Directories: The storage and bootstrap/cache directories need to be writable.
URL Rewriting
For cleaner URL structures, setting up URL rewriting is mandatory:
Apache Setup:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Nginx Setup:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
Scheduled Tasks
Laravel uses CRON to run scheduled jobs, often present at * * * * * cd /path-to-your-project && php
artisan schedule:run >> /dev/null 2>&1.
VHost Configuration
Additional Apache Directives:
<Directory "/path-to-your-project">
AllowOverride All
</Directory>
Nginx Configuration:
location / {
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}
Version-Specific Adjustments
PHP 8: Use Laravel 8.x or higher.
PHP Modules: Cyrillic support necessitates the presence of the php-intl module.
2. Initialize Project: Run composer install to build the initial directory structure and install required packages.
3. Environment Configuration: Create a .env file from .env.example for environment-specific settings.
4. Encryption Key: Generate a unique application key with the php artisan key:generate command.
5. Database Setup: Specify database credentials in .env. Execute php artisan migrate to set up the
database schema if using migrations.
6. Serve the Project: Use php artisan serve to launch the web server and access the project at the provided
URL.
7. Set Permissions: Ensure the storage and bootstrap/cache directories are writable.
8. Optional Steps:
Frontend Setup: Laravel Mix bridges assets like CSS, JS, and images. Run npm install within the
Laravel project directory to get started.
SMTP Configuration: If enabling email functionality, update the .env file with SMTP credentials.
This command installs the latest version of Laravel in a folder named blog. Use any proper Laravel directory name of
your choice.
APP_NAME=Laravel
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_UNIQUE_KEY
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Recommendations
Version Controlling: Utilize Git for source control right from the project's inception.
Environment-Dedicated Tooling: Tailor development and deployment tooling based on the environment to
streamline workflows further.
Core Concepts
Verb: Refers to the HTTP action, e.g., GET, POST, PUT, DELETE.
URI: The specific path that leads to the requested resource.
Action: Ties the request to a specific method in a defined controller.
Routing in Laravel
Laravel offers two primary methods for handling routes:
1. Implicit: Involves direct handling of routes. This approach is better suited for simple systems.
2. Explicit: Utilizes routing definitions that cater to specific HTTP verbs and respond to named URIs, offering a
structured routing system.
Implicit Routing
Definition
In this approach, routes are defined directly in code using \Illuminate\Routing\Router methods; most commonly,
get and post.
Example
Route::get('/profile', 'UserController@showProfile');
Use Case
Explicit Routing
Definition
Laravel stores explicit route definitions in the routes directory, potentially organized within multiple files.
Standard HTTP actions like GET, POST, PUT, DELETE have corresponding methods for explicit routing: get, post, put,
and delete. Laravel also offers the match and any methods for flexibility.
Example
Route::get('/users', 'UserController@index');
Named Routes
This feature assigns unique names to routes, enabling easy access for operations like URL generation and redirection.
Example:
Route Groups
Groups furnish a clean way to administer routes that have common attributes, such as middleware requirements or
shared URIs.
Example:
Route::prefix('admin')->middleware('auth')->group(function () {
// Define the admin routes
});
Flexible Routing
Route Parameters: Laravel permits the definition of routes with dynamic segments, denoted by {}. These
dynamic segments can be captured and utilized.
Example:
Optional Parameters: For more flexibility, a route may specify segments as optional, evident by the use of a
question mark.
Example:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Regular Expression Constraints: To exercise fine-grained control, constraints make it possible to specify the
format of a route segment using regular expressions.
Example:
Special Routes
Falling Back with Fallback Routes: Laravel can be configured to utilize a "fallback" route when no other routes
match the incoming request. Often used in the context of SPAs.
Example:
Route::fallback(function () {
return view('notfound');
});
Middleware in Action
When an HTTP request hits your Laravel application, it moves through several middleware before reaching the intended
controller or view. These are some frequently-seen operations achieved by middleware:
Authentication: Ensure that the user issuing the request is authenticated before reaching the application logic.
Authorization: Once authenticated, verify that the user has the necessary permissions to access the particular
resource or perform the requested action.
Logging: Capture details about the incoming request, such as the requesting IP address, HTTP method, or
parameters.
Session Handling: Manage user sessions, which permits web applications to oversee user states across multiple
requests.
Input Verification and Sanitization: Inspect and cleanse the incoming data to avoid potential security threats,
such as Cross-Site Scripting (XSS) attacks or SQL injection.
3. Execution Pipeline: Middleware execute in sequence, each having the option to terminate the pipeline or pass
the request to the next middleware.
4. Processing: The middleware might perform certain tasks or modifications, such as log requests or redirect
unauthenticated users.
5. Controller/ Response: Once the full middleware stack is traversed, the request proceeds to the associated
controller or directly returns a response, bypassing the controller.
Chain of Responsibility
Middleware in Laravel embraces the Chain of Responsibility design pattern. Each middleware is responsible for a specific
type of task or validation. Following middleware only comes into play if the previous ones pass or fail according to certain
criteria.
The middleware stack begins with a guard that ensures the user is logged in.
If the user is authenticated, it proceeds to the next middleware. If not, the request might be redirected to a login
page.
Here is an example of how you can create custom middleware using the Laravel artisan command:
Middleware Groups
Laravel provides a feature to cluster one or more middleware into groups for straightforward management and application.
This simplifies the process of associating several middleware with a specific route or set of routes.
The middleware groups are defined in the app/Http/Kernel.php file under an array called middlewareGroups. For
instance, a default 'web' middleware group may invoke middleware like EncryptCookies,
CheckForMaintenanceMode, and Authenticate that are pertinent for web requests. Developers can also create their
custom groups catering to their unique needs, like one for API, system administration, etc.
After configuring the groups in Kernel.php, routes can trigger these middleware groups using the middleware method.
Global Middleware
Occasionally, there might be a need for certain middleware to be applied to every HTTP request, such as logging or
CORS (Cross-Origin Resource Sharing) handling. Laravel caters to this requirement through a concept known as global
middleware.
Global middleware is registered in the app/Http/Kernel.php file under the $middleware property. Any middleware
listed here will be executed on every HTTP request, irrespective of the route or route group. It's important to exercise
caution when selecting middleware for global status, as it could significantly affect the application's performance and
correctness.
Key Components
HTTP Middleware: Delivers a modular approach to filtering HTTP requests and responses.
Request: Transforms HTTP requests into an instance of Request.
Router: Matches the URI to an appropriate route.
Controller: Processes the incoming request.
Middleware Groups: Organize several middleware under a single, distinctive name.
Response: Turns controller return results into HTTP responses.
Global Middleware: Applies to all HTTP requests.
Following an HTTP request, \textbf{the public/index.php file is called}. This initializes the Laravel
framework.
// public/index.php
require __DIR__.'/../vendor/autoload.php';
Quest travels through the Bootstrap layer and lands in the Kernel. However, Middleware is not yet
applied.
2. HTTP Kernel:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
// More global middleware go here
];
3. Routing:
HTTP Kernel and the Request synchronizes to identify the most suitable route.
Appropriate route data, such as controller and method names, is discovered.
Named middleware is assigned, if any.
Route::get('/', 'HomeController@index')->middleware('auth');
4. Controller:
The route delegates the quest to an assigned controller together. The method on the controller then
processes the quest.
If applicable, the controller method returns a response. Laravel, naturally, transforms this into an HTTP
response.
5. Response:
The created response passes through \textbf once again, if there might exist any.
Lastly, Laravel sends the response back to the customer.
The response life cycle ends, together with the quest itself.
Key Responsibilities
Registering Services: This includes services such as repositories, interfaces, and any binding within the Laravel
service container (App::make()).
Bootstrapping and Configuration: Provides a platform to set up the application's initial state before it boots up.
Registration
Service providers are mostly registered in the config/app.php file.
Boot Method
While Service Providers have a register method for simple bindings, also they have a boot method for more
complex procedures such as registering event listeners or even defined routes.
By including these clear architectural distinctions, the Laravel framework ensures a modular, maintainable, and scalable
design.
In Eloquent, each database table has a corresponding "Model" which is used to interact with that table. Models and
relationships in Eloquent allow for common database tasks without requiring direct SQL queries.
2. Portability: Models and the relationships between them make it simple to move code between different database
systems (e.g., from MySQL to SQLite or PostgreSQL).
3. Scalability: Eloquent provides a simple and clean way to define relationships between tables, ensuring the code
scales effectively.
4. Refactoring: If the database schema changes, often only the model needs to be updated. Eloquent abstracts
these changes from the rest of the codebase.
Basic CRUD Operations: Eloquent makes it simple to create, read, update, and delete records using the familiar
object-oriented syntax.
Model Events: Perform actions during certain events such as when a new model is saved or updated.
Query Scopes: Pre-define filtering criteria to make common queries concise and consistent.
Data Accessors & Mutators: Fine-tune how data is retrieved or set on the model.
2. Eloquent Relationships
One-to-One: Defines a one-to-one relationship between two tables, such as a User and a Phone table.
One-to-Many: Establishes a one-to-many relationship, for instance, a user can have many posts.
Many-to-Many: Describes a many-to-many relationship using an intermediate table, like tags on a blog post.
Polymorphic Relations: Eloquent models can relate to multiple types of models using a single association.
Has Many Through: Provides a relationship between "three" models through a "through" table.
3. Database Querying
Relationship Eager Loading: Minimizes the number of queries to the database when fetching relationships.
Aggregates: Sum, count, and other SQL aggregates are supported for quick operations.
3. Fail Early: Utilize strict type casting and validation to catch issues at the earliest opportunity.
4. Stay Efficient: Make your queries as efficient as possible by utilizing the many optimising features of Eloquent.
5. Test Thoroughly: Always validate your model's methods and relationships to ensure they perform as expected.
3. Fail Early: Utilize strict type casting and validation to catch issues at the earliest opportunity.
4. Stay Efficient: Make your queries as efficient as possible by utilizing the many optimizing features of Eloquent.
5. Test Thoroughly: Always validate your model's methods and relationships to ensure they perform as expected.
1. Create a Controller: Define methods for HTTP verbs like store() for POST requests. In these methods, use the
validate() helper. If the validation fails, Laravel automatically redirects back to the previous location.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Controller Validation
By using the validate() method within the Controller, Laravel provides all necessary details about the validation failure,
such as:
Immediate Feedback
Upon successful validation, the $validatedData array holds the cleared data, ready for further processing.
For the more traditional workflows such as a direct page render (no redirects), or API responses, Laravel offers the
Validator facade. It enables extensive customization before the final decision on the error handling.
By providing defined methods, Laravel Contracts ensure interoperability between various components and services. This
results in an environment where different pieces of the ecosystem can 'contract' to a set of specified behaviors. This helps
in maintaining loose coupling between software components.
Key Benefits
Consistency: Contracts enforce a common structure for interacting components.
Flexibility: They facilitate interchangeable implementations for services.
Ease of Testing: Contracts enable robust unit testing by ensuring precise behavior specifications.
Documentation: They serve as explicit documentation, detailing required methods and expected responses for
services and components.
Practical Examples
Laravel itself employs Contracts extensively in its codebase. For instance, the Cache facade abstracts from various
implementation details and relies on the CacheRepository contract to standardize caching drivers' functionality.
The primary CacheRepository interface serves as a contract for various caching methods. It is complemented by other
interfaces, such as StoresQualities, which further define specialized functionalities. The close association between
these interfaces results in a cohesive system where individual parts target specific capabilities.
CacheRepository Interface
interface CacheRepository {
public function get($key);
public function put($key, $value, $minutes);
public function forget($key);
Then, you can have a more specialized interface like StoresQualities that focuses on cache item manipulation
through qualities.
StoresQualities Interface
interface StoresQualities {
public function incrementQuality($key, $value);
public function touch($key);
Extended Directories
7. routes: Segregates application routes. Newer versions further divide routes by function or area, e.g., 'api' and
'web'.
8. storage: Stores logs, cache, and uploaded files. Particularly, 'storage/app' houses uploads, ensuring they are not
within the public web space.
Housekeeping Directories
9. tests: A dedicated directory for automated tests.
10. vendor: Manages dependencies via Composer, housing third-party libraries.
Auxiliary Directories
11. health: For health-check related code. Laravel Sanctum, for instance, uses this for API health endpoints.
12. jobs: Addresses data queueing, often in conjunction with Laravel's powerful job and queue systems.
13. nova: For Laravel Nova, a premium, official, modern administration panel.
14. settings: Utilized by beyondcode/laravel-settings to manage application-level settings.
15. stubs: Facilitates customizable templates for automated routines, such as controller or model generation.
16. sail: Tailors Laravel for use with Laravel Sail, a local development environment focused on a Docker configuration.
17. tmp: A conventional temp directory for short-term file storage.
vendor/bin, public/sanctum: These are not standard directories but commonly seen when dealing with
Composer scripts (vendor/bin) or Laravel Sanctum.
By default, Laravel uses MySQL. However, you can easily configure it to work with a variety of databases such as
PostgreSQL, SQLite, and more.
Define the connection details in the .env file, including the database type, host, port, and credentials.
2. config/database.php:
Laravel configures the database connection dynamically based on the settings in the .env file. For more
specific settings, you can modify the config/database.php file.
Use Laravel's migration files to maintain your database and models to interact with tables.
4. Eloquent ORM:
5. Database Methods:
Execute database queries using Laravel's query builder and raw SQL methods.
Load dummy data into your tables using seeders. This is especially useful during testing.
Select the database service for cache and session storage. Using the same database for cache and
sessions can provide consistent state management in certain situations.
After configuration, verify the connection by running artisan commands like migrate or using a web
interface.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=root
DB_PASSWORD=your_password
/**
* PostgreSQL Databases
*/
'pgsql' => [
'driver' => 'pgsql',
...
],
/**
* SQLite Databases
*/
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
Laravel offers flexibility in configuring multiple SQL and NoSQL databases, all managed through a unified interface.
Core Functionalities
Versioning the Database
Migrations maintain a version history for the database schema, ensuring consistency across development,
staging, and production environments.
Each migration has a timestamp, resulting in a natural order for executing changes, making it easier for teams to
coordinate DB updates.
Easy Rollbacks
Laravel provides a simple command to roll back the last migration or even up to a specified step, ensuring
revertibility.
Laravel automates the generation of code for common database tasks. This both increases developer productivity
and reduces the chance of errors due to manual coding.
Ephemeral Databases for Tests: Laravel's testing suite uses migrations to create and destroy temporary, in-
memory databases for test runs, ensuring data isolation and reproducibility.
Increased Security: Migrations support parametrized SQL queries, reducing vulnerabilities such as SQL injection.
Data Consistency: Migrations provide mechanisms to orchestrate data changes alongside structural ones,
ensuring both take effect in a synchronized manner.
Standardization: Provides a consistent and structured approach to database management across development
and production.
Traceability: Migrations are version-controlled, offering clear histories and facilitating audit processes.
Agility: Because both schema and data changes are controlled via migrations, making changes, and adapting the
database to evolving requirements can be quicker and more reliable.
Synchronous Collaboration: Migrations allow developers to work in parallel, making database changes without
stepping on each other's toes, and then integrating those changes back into a single unified state.
Streamlined Deployment: Using migrations during deployment transmits database changes efficiently and
reliably between development and production environments.
15. What is the command to create a
controller in Laravel?
To create a controller in Laravel, use the following artisan command:
Here YourControllerName specifies the desired controller name. You can also use dot-notation for nested directories
(Folder/YourControllerName).
API Resource Controllers: These are specifically for RESTful APIs, providing a reduced set of actions compared
to full resource controllers.
Invokable Controllers: If you need a single-action controller, you can use the --invokable flag. This is useful,
for example, when working with Route::resource.
Controller with Model: To combine model and controller creation, you can use -m or --model.