Support the ongoing development of Laravel.io →
Article Hero Image

How to become Fluent in Laravel

15 Jan, 2023 6 min read

Photo by kazuend on Unsplash

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
];

You access any property using the following syntax:

echo $product['name'];

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'];

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

Undefined array key 'sku'

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
];

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

echo $product['name'];

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

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
{ }

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
]);

Then you can access the properties as follows:

echo $product->name;

// or

echo $product[‘name’];

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);

Then you can access the properties like so:

echo $product->name;

// or

echo $product[‘name’];

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);

Then access the properties like this:

echo $product->name;

// or

echo $product[‘name’];

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');

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);

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;

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;

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);

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.

Last updated 3 weeks ago.

driesvints, peterfox, mostafa-amine, lupete, highfishmarket, maddychennupati, duwscan liked this article

7
Like this article? Let the author know and give them a clap!
bhaidar (Bilal Haidar) Hey there 👋! I am Bilal, Founder & CEO at Let's Remote. I'm a highly skilled web developer with 16+ years of experience. Laravel is my bread and butter.

Other articles you might like

Article Hero Image November 18th 2024

Laravel Custom Query Builders Over Scopes

Hello 👋 Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to r...

Read article
Article Hero Image November 19th 2024

Access Laravel before and after running Pest tests

How to access the Laravel ecosystem by simulating the beforeAll and afterAll methods in a Pest test....

Read article
Article Hero Image November 11th 2024

🍣 Sushi — Your Eloquent model driver for other data sources

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.