Tag Archives: Laravel

Collections In Laravel


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.


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

CSRF Middleware in Laravel 5


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:

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.