DEV Community

Cover image for How to become Fluent in Laravel
Bilal Haidar
Bilal Haidar

Posted on • Edited on

How to become Fluent in Laravel

Fluency in Laravel can take several forms. One of them is using the Fluent class hidden inside the Laravel framework.

The Fluent class is a utility class provided by the Laravel framework that allows you to create and manipulate objects fluently. This means you can chain together method calls and property assignments in a more expressive and readable way without nesting long chains of method calls or using complex arrays.

The Fluent class is beneficial when you build up an object with many properties, allowing you to set and manipulate these properties more concisely and expressively. It is also useful when accessing object properties using dot notation rather than array notation.

Overall, the Fluent class is an essential tool for working with objects in Laravel and is widely used throughout the framework to provide a more readable way to work with data.
This article will explore how you can use the Fluent class to create and manipulate objects in Laravel.

Table of Contents

Introduction

  • Definition of Fluent class in PHP Laravel
  • Explanation of its purpose and uses

What’s wrong with Associative Arrays

Creating a Fluent Object

  • How to create a Fluent object using the make method
  • How to create a Fluent object using an existing Array
  • How to create a Fluent object using an existing Object
  • How to use the with() method to add additional properties to a Fluent object
  • How to create a Fluent object using the fluent API

Manipulating Fluent Objects

  • How to access the properties of a Fluent object using dot notation
  • How to set the properties of a Fluent object

Conclusion

  • Recap of the purpose and uses of the Fluent class in PHP Laravel

What’s wrong with Associative Arrays?

Associative Arrays are a useful data structure for storing key-value pairs commonly used in PHP applications.

Let’s take an example of using an Associative array to store a Product record.

$product = [
    'id'    => 1,
    'name'    => 'Nike Air Force 1',
    'price'    => 50000, // cents
];
Enter fullscreen mode Exit fullscreen mode

You access any property using the following syntax:

echo $product['name'];
Enter fullscreen mode Exit fullscreen mode

This line prints out the name of the product.

Now let’s try to access a non-existing property on this array:

echo $product['sku'];
Enter fullscreen mode Exit fullscreen mode

The sku property doesn’t exist on the array. PHP, in this case, throws an ErrorException with this message:

Undefined array key 'sku'
Enter fullscreen mode Exit fullscreen mode

Let’s take another example. Assume we define the Product as an instance of sstdClass rather than an Associative array.

$product = (object) [
    'id'    => 1,
    'name'    => 'Nike Air Force 1',
    'price'    => 50000, // cents
];
Enter fullscreen mode Exit fullscreen mode

Now, let’s try to access the Product name:

echo $product['name'];
Enter fullscreen mode Exit fullscreen mode

You are trying to access a property on an instance of stdClass using the array notation. PHP, in this case, throws an error exception with this message:

Cannot use object of type stdClass as array
Enter fullscreen mode Exit fullscreen mode

Working with Associative Arrays or mixing Objects with Arrays can sometimes be risky and inefficient.

Wouldn’t it be better to have one common API to access both Arrays and Objects similarly without worrying about exceptions or invalid syntax use?
Well, there is; the Fluent class comes with the Laravel Framework.

Creating a Fluent Object

Using the Fluent class can be more convenient than using an associative array in certain situations. It allows you to access object properties using dot notation rather than array notation.

The Fluent class is defined inside the Illuminate\Support namespace.

<?php


namespace Illuminate\Support;

class Fluent implements Arrayable, ArrayAccess, Jsonable, JsonSerializable
{ }
Enter fullscreen mode Exit fullscreen mode

It implements the Arrayable, ArrayAccess, Jsonable, and JsonSerializable interfaces. Using a Fluent class, you can access properties using the Array and dot-notation syntax.

Let’s look at a few examples of how to use the Fluent class.

How to create a Fluent object using the make method

To define a new instance of a Fluent class, you may use the make() method as follows:

$product = new Fluent::make([
    'id'    => 1,
    'name'    => 'Nike Air Force 1',
    'price'    => 50000, // cents
]);
Enter fullscreen mode Exit fullscreen mode

Then you can access the properties as follows:

echo $product->name;

// or

echo $product[name];
Enter fullscreen mode Exit fullscreen mode

Notice how we can use both Array or dot-notation forms of access.

How to create a Fluent object using an existing Array

Not only can you create an instance of the Fluent class using the make() method, you can wrap your existing Array using the Fluent class constructor as follows:

$data = [
    'id'    => 1,
    'name'    => 'Nike Air Force 1',
    'price'    => 50000, // cents
];

$product = new Fluent($data);
Enter fullscreen mode Exit fullscreen mode

Then you can access the properties like so:

echo $product->name;

// or

echo $product[name];
Enter fullscreen mode Exit fullscreen mode

How to create a Fluent object using an existing Object

The Fluent class can also wrap an Object, not only an Array. Here’s an example:

$data = new Product(
        id: 1,
        name: 'Nike Air Force 1',
        price: 50000, // cents
);

$product = new Fluent($data);
Enter fullscreen mode Exit fullscreen mode

Then access the properties like this:

echo $product->name;

// or

echo $product[name];
Enter fullscreen mode Exit fullscreen mode

Notice how we can use both Array or dot-notation forms of access.

How to use the with() method to add additional properties to a Fluent object.

Let’s say you are wrapping an existing array in a new instance of the Fluent class and want to add additional data. In this case, you should use the with() method:

$data = new Product(
        id: 1,
        name: 'Nike Air Force 1',
        price: 50000, // cents
);

$product = new Fluent($data)->with('sku', '123AVC');
Enter fullscreen mode Exit fullscreen mode

The $product object now has four properties, including the sku.

How to create a Fluent object using the fluent API

The third and last method of creating an instance of the Fluent class is by using the fluent API as follows:

$product = (new Fluent)
->id(1)
        ->name('Nike Air Force 1')
        ->price(50000);
Enter fullscreen mode Exit fullscreen mode

And you can access it usually as you would access any instance of the Fluent class.

Accessing a non-existing property on a Fluent object

We have seen before that when you access a non-existing property on an Associative array, PHP throws an ErrorException.

What do you think happens when you access a non-existing property on a Fluent object?

$product->created_at;
Enter fullscreen mode Exit fullscreen mode

The line above returns null. No exceptions are thrown.

You can appreciate the value of the Fluent class over Associative arrays and Objects.

Manipulating Fluent Objects

You can use a Fluent object not only to access a property but also set the value of a property.

You have two options to set a property value: the array syntax or the dot notation. Let’s see an example:


$data = new Product(
        id: 1,
        name: 'Nike Air Force 1',
        price: 50000, // cents
);

$product = new Fluent($data);

$product['price'] = 60000;

// or

$product->price = 60000;
Enter fullscreen mode Exit fullscreen mode

You can also unset the value of a property using the unset() method, that’s part of the PHP standard library.

unset($product[price]);

// or

unset($product->price);
Enter fullscreen mode Exit fullscreen mode

Conclusion

The Fluent class in PHP Laravel is a utility class that allows developers to create and manipulate objects in a more readable and expressive way. It is beneficial when working with objects with many properties, enabling them to be set and manipulated concisely. The Fluent class can be created using the make method, an existing array or object, or the fluent API. It can be manipulated by accessing and setting its properties using dot notation.

Overall, the Fluent class is an essential tool for working with objects in Laravel and is widely used throughout the framework to provide a more expressive and readable way to work with data.

Top comments (3)

Collapse
 
alnahian2003 profile image
Al Nahian

Now the question is, Fluent or DTO?

Collapse
 
whchi profile image
whchi

nice trick, but when will you use this?

Collapse
 
jomisacu profile image
jomisacu

Always! Think about something like this:

$post = new Fluent($_POST);

Obviously in Laravel context you have a lot of ways to get request data, but this is for illustration. By this way you can access to post data without think in warnings or notices. You can forget the repetitive isset check, and replace if (isset($post['key']) && $post['key']) by a simple if ($post['key']).

And more, there are a lot of situations where this type of flexibility is very convenient. e.g. when you have a collection of different structures (different types, different keys, objects, arrays) is very convenient can check in the same way for all items in the collection. Think about payload from an editor composed by different block types: text, gallery, title, custom. In this way you will not worried about block types, you only check in a "Fluent" way the identity and the props for each block.