Category Archives: Laravel

Facade in Laravel

facede-larvel

What is Facade

Facades provide a “static” interface to classes that are available in the application’s service container(managing class dependencies and performing dependency injection(class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.) ).

Laravel facades serve as “static proxies” to underlying classes in the service container, providing the benefit of a short, expressive syntax while maintaining more flexibility(In terms of configuring class/libraries being used) than traditional static methods.

All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.

How Facades Work

In a Laravel application, a facade is a class that provides access to an object from the service container. The machinery that makes this work is in the Facade class. Laravel’s facades, and any custom facades you create, will extend the base Illuminate\Support\Facades\Facade class.

The Facade base class makes use of the __callStatic() magic-method to defer calls from your facade to an object resolved from the container.

In the below lines , a call is made to the Laravel cache system. By looking at code, one might assume that the static method get is being called on the Cache class:

<?php

use Illuminate\Support\Facades\Cache;

function someMethod(){
    $id = 'abc'; //some key on which data is saved
    $user = Cache::get($id);
    
}

//If we look at that Illuminate\Support\Facades\Cache class, you'll see that there is no static method named get:

class Cache extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'cache'; }
}

If we look at that Illuminate\Support\Facades\Cache class, you’ll see that there is no static method named get:

Instead, the Cache facade extends the base Facade class and defines the method getFacadeAccessor(). This method’s job is to return the name of a service container binding.

When a user references any static method on the Cache facade, Laravel resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.

Collections In Laravel

Introduction

We can think Collection as Objects of objects. It works as a wrapper over an array by providing some more methods. As every item in Collection have some objects, It will be able to give some extra features like (Paging results, Checking for odd or even, ->isOdd(), etc.)

In general a collection can be referred as a set that can contain any can kind of data object like (Array, ArrayList(In java), LinkedList, Vector, Stack, Queue, etc.)

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We’ll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
->reject(function ($name) {
return empty($name);
});

As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array.

In general, collections are immutable(means to say unchangeable in nature), and every Collection method(applied in chaining) returns an entirely new Collection instance.

e.g. We can look something like.

Collection2 = Collection1->methodOne(); // will return a new collection named Collection2
Collection3 = Collection2->methodTwo(); // will return a new Collection named Collection3

Above two lines are equivalent to a single line as below,

Collection3 = Collection1->methodOne()->methodTwo();

Collection class is able to provide many methods few of them are –

all, average, avg , chunk, collapse, combine, contains, containsStrict, count, diff, diffAssoc, diffKeys, each, every,except.

Examples


collect([1, 2, 3])->all();

// [1, 2, 3]

$average = collect([['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40]])->avg('foo');
// 20

$average = collect([1, 1, 2, 4])->avg();

// 2

Laravel Eloquent vs Query Builder

Eloquent Models

Eloquent is Laravel’s implementation of Active Record pattern for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. and it comes with all its strengths and weaknesses. It is a good solution to use when you process a single entity in a CRUD manner – that is, read from database or create a new entity and then save it or delete. You will benefit a lot from Eloquent’s features such as dirty checking (to send SQL UPDATE only for the fields which have been changed), model events (e.g. to send administrative alert or update statistics counter when someone has created a new account), traits (timestamps, soft deletes, custom traits) eager/lazy loading etc.

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all. Also Eloquent has ton of extra features the the query builder lacks, such readability, accessors, mutators, JSON/Array conversion, hiding sensitive attributes, automatic timestamps, automatic attribute casting, softdeletes.

But, as you already know, it comes with some performance price. When you process a single or just a few records, there is nothing to worry about. But for cases when you read lots of records (e.g. for datagrids, for reports, for batch processing etc.) the plain DB is better approach.

Fluent query builder

Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

The Laravel’s query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

NOTE: All methods available to Query Builder are available to Eloquent too, But method available to Eloquent Models is not available to Fluent, In short We can see Eloquent as a wrapper class over Query Builder.

CSRF Middleware in Laravel 5

CSRF

Working of CSRF Middleware in Laravel 5

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF “token” for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

The VerifyCsrfToken middleware, which is included in the web middleware group, will automatically verify that the token in the request input matches the token stored in the session.

Laravel 5 enables the VerifyCsrfToken middleware by default for all requests that is using webmiddleware . It works as below:

#1- Check if the request is a reading request (HEAD, GET, OPTIONS). If so, skip the check.
#2- Matches the token from the _token input or from the headers.
#3- Add a cookie with the token to each request.

This makes the CSRF check a lot more flexible. You don’t have to remember where to add you filters, just make sure that every form has a _token field. Because of #2 and #3, it will work with Ajax request without having to modify the core filter.

Note: This reminds us again that GET requests should never change state(More precisely GET Request are meant to retrieve the data from server, rather than make any kind of update to server database). The CSRF middleware assumes that it doesn’t need to check GET (or HEAD/OPTIONS) requests, because they should be safe to execute.

Checking the headers

At first, only the X-XSRF-TOKEN was checked. This used the Angular convention that the token could be read from the XSRF-TOKEN cookie. If Angular detects that cookie, it adds the token to all XHR requests.

var xsrfValue = urlIsSameOrigin(config.url)
? $browser.cookies()[‘XSRF-TOKEN’]
: undefined;
if (xsrfValue) {
reqHeaders[‘X-XSRF-TOKEN’] = xsrfValue;
}

While this does work great for Angular, it has a slight problem: Because the cookies in Laravel are always encrypted, the token from the cookie needs to be decrypted before it can be compared. This is not a problem for Angular, but it is a problem if you want to set the header manually for your own Javascript requests.

In Laravel 5.0.6, there is added support for a plain text X-CSRF-TOKEN header.

input('_token') ?: $request->header('X-CSRF-TOKEN');
if ( ! $token && $header = $request->header('X-XSRF-TOKEN'))
{
$token = $this->encrypter->decrypt($header);
}
return StringUtils::equals($request->session()->token(), $token);
}

You could now simply add a meta-tag to your section, read it with jQuery and set the XHR header:

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Above will set the token header for all your jQuery requests.

Hope it may be making a few more clarifications.