Introduction to Laravel and its features
What is laravel?
Laravel is an open source PHP web application framework.It was developed by Taylor Otwell and released in june 2011.Reasons to use laravel includes the various features listed below:
Robust Routing System:
It uses a Robust Routing System which allows us to define URL endpoints and map them to their appropriate controller methods.It also lets us name them.
Example:
// routes/web.php
Route::get('/greet', 'GreetingController@greet')->name('greeting');
Model View Controller:
It uses the Model View Controller (MVC) architecture pattern.This helps us to seperate business logic from presentation and application logic.It makes our code more modular, maintainable and testable.
Model: Model is represent by Eloquent ORM which is an Object Relational Mapping system of Laravel. Models serve as an ORM (Object-Relational Mapping) layer, allowing developers to interact with database tables as if they were PHP objects.It allows us to write SQL queries in PHP code and manage database tables and relationships. We can define data schema,relationship between models and data access and manipulation methods.
Business Logic to manage Post data of a blog:
<?php
namespace App\Models; # here Models is the name of folder
use Illuminate\Database\Eloquent\Model; # this is Model class
class Post extends Model
#fillable property specifies 'attributes' in an array that can be mass assigned to the model
{
protected $fillable=[
'title',
'body',
];
public function user()
# here user method defines relationship between post model and user model#fillable property specifies 'attributes' in an array that can be mass assigned to the model
{
return $this->belongsTo(User::class)
}
public function publish()
# publish method defines the business logic for publishing a blog post upon calling.It sets published at attribute to current time and saves it to database.
{
$this->published_at = now();
$this->save();
}
}
View: It is the presentation layer of laravel. Blade is a templating engine used by Laravel PHP framework.It provides an easy and intuitive way to create templates for web applications.
- It uses plain PHP
- Allows easy manipulation with control structures, loops, conditionals and expressions.
- Code Re-usability: Blade templates can be reused across multiple pages.
- Fast in rendering views: When the blade view is first rendered the compiled PHP code is cached.
- Layouts: Allows developers to define layouts that can be used to structure contents of page which reduce amount of code that needs to be written.
- Custom Directives(): We can define it in service provider or directly in a view
Blade::Directive() method is used to create custom directives.
Middleware Support:
Middleware is a series of filters that can be applied to HTTP requests before they are processed by the application. Middleware helps us to handle:
- authentication
- authorization
- other security related tasks etc.
Built in authentication and authorization:
Laravel provides an authentication system that can be easily customized to fit the needs of an application.
- Supports authentication methods such as email and password verification. Two factor authentication etc.
- Authorization system: Laravel framework includes policies,gates,middleware which help us to define complex authorization rules and access controls.
- Password resets: helps us to send password reset links via email easily.
- Throttling: Laravel includes a built in throttling system that can be used to limit the number of requests. Helpful in preventing brute force attacks or attacks that rely on sending large number of requests to an application.
CSRF Protection:
Laravel includes built in Cross Site Request Forgery protection, which helps to prevent attackers from submitting malicious requeststo the application.
The CSRF protection works by generating a unique token for each user session, which is included in each form submission to ensure that the request is legitimate.
If we do not include the CSRF token or forget to include it we get a 419 page expired error.
Queues and scheduled tasks:
Laravel provides a queue system that allows developers to defer the processing of time-consuming tasks, making applications more responsive.It also has a scheduling system that allows developers to schedule periodic tasks to run automatically.
Testing and debugging:
Laravel provides us with a testing framework PHPUnit for unit and feature testing.
Types of tests:
Unit Test: It is used to test individual units or components of software in isolation(eg: methods, functions).
php artisan make:test TestName --unit #this will generate a unit test
Feature Test: It is used to test a piece of functionality as a whole often involving a lot of units working together.
php artisan make:test TestName
Tests in laravel are stored in the test directory.
example:
public function testExample()
{
this->assertTrue(true);
}
Debugging in Laravel:
Debugging is the process of finding and resolving issues within a software application.
a) Laravel Debugbar: One of the most popular debugging tools for Laravel is the Debugbar. It provides detailed insights into your application’s performance, queries, and other essential metrics.
composer require barryvdh/laravel-debugbar --dev
After installation, the Debugbar will automatically appear at the bottom of your application when accessing it in a local environment.
b) Laravel Telescope: Laravel Telescope is an elegant debugging assistant provided by Laravel. It offers insights into the requests coming into your application, exceptions, database queries, queued jobs, mail, notifications, and more.
php artisan telescope:install
php artisan migrate
Run the above commands and you can access telescope by visiting /telescope in your app.
Log files:
All laravel exceptions and errors are logged in the storage/logs directory. Monitering these logs can be a quick way to diagnose issues.
Conclusion
Laravel provides modular and easily maintainable codebase which makes it ideal for building web applications of varying sizes. It also provides a plethora of tools and features that make this process streamlined and efficient for developers. Always remember to use the available tools wisely.
Happy Coding!