Using `tap()` Helper Function in Laravel
In Laravel, the `tap()` helper function is a powerful utility that allows you to perform actions on a value within a callback function and then return that same value.
Laravel

`tap()` Helper Function in Laravel

 

In Laravel, the `tap()` helper function is a powerful utility that allows you to perform actions on a value within a callback function and then return that same value. It can be handy in situations where you need to perform some operations on an object or variable while keeping the code concise and readable. In this tutorial, we will explore how to use `tap()` with code examples and real-world scenarios.

 

Syntax

 

The syntax of the `tap()` function is straightforward:

 

tap($value, function ($value) {
    // Perform operations on $value
    // Return $value
});

 

The function takes two arguments:

1. `$value`: The value on which you want to perform operations.
2. $callback: A closure that takes `$value` as its argument, performs operations, and returns the modified `$value`.

 

Code Examples

 

Let's dive into some code examples to understand the practical usage of the tap() function.

 

Example 1: Modifying an Array

 

Suppose we have an array of numbers, and we want to double each number in the array using `tap()`:

 

$numbers = [1, 2, 3, 4];

tap($numbers, function ($numbers) {
    $result = [];
    foreach ($numbers as $number) {
        $number *= 2;
        array_push($result, $number);
    }
    print_r($result);
});

 

Output:

 

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
)

 

In this example, `tap()` takes the `$numbers` array, doubles each element using the callback function, and returns the modified array. The original `$numbers` array remains unchanged.

 

Example 2: Eloquent Model Manipulation

 

Let's use `tap()` to create and save a new Eloquent model instance:

 

use App\Models\Post;

$newPost = tap(new Post(), function ($post) {
    $post->title = 'New Post';
    $post->content = 'This is a new post created using tap()';
    $post->published = true;
    $post->save();
});

 

In this example, we create a new `Post` model instance, set its attributes, save it to the database, and store it in the `$newPost` variable. The `tap()` function allows us to chain the attribute assignment and the save operation while keeping the code concise and readable.

 

Real-World Example: Laravel Validation

 

In this example, we'll use `tap()` to validate form input and store validated data in the database:

 

use Illuminate\Http\Request;
use App\Models\Post;

public function store(Request $request)
{
    $validatedData = tap($request->validate([
        'title' => 'required|string|max:255',
        'content' => 'required|string',
    ]), function ($validatedData) {
        Post::create($validatedData);
    });

    return redirect()->route('posts.index')->with('success', 'Post created successfully!');
}

 

In this scenario, `tap()` is used to validate the form data and return the validated data. The callback function then creates a new `Post` model instance using the validated data and stores it in the database.

 

Real-World Example: Laravel Collections

 

In the following example, we will use the `tap()` function with Laravel collections to perform operations on the collection and then return the modified collection. 

Suppose you have a collection of products, and you want to apply some filters and transformations to it using `tap()`.

 

use Illuminate\Support\Collection;

// Sample collection of products
$products = collect([
    ['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['name' => 'T-shirt', 'price' => 25, 'category' => 'Clothing'],
    ['name' => 'Phone', 'price' => 800, 'category' => 'Electronics'],
    ['name' => 'Shoes', 'price' => 60, 'category' => 'Footwear'],
]);

$filteredAndTransformedProducts = tap($products, function ($products) {
    // Apply filters: Select only Electronics category products and remove products below $100.
    $filteredProducts = $products->where('category', 'Electronics')
                                ->where('price', '>', 100);

    // Apply transformation: Double the price of each product.
    $transformedProducts = $filteredProducts->map(function ($product) {
        $product['price'] *= 2;
        return $product;
    });

    // Return the modified collection.
    return $transformedProducts;
});

 

 

After executing the code above, the `$filteredAndTransformedProducts` variable will contain the modified collection with the Electronics category products having prices doubled and filtered based on the price condition.

Here's the output:

 

Illuminate\\Support\\Collection Object
(
    [items:protected] => Array
        (
            [0] => Array
                (
                    [name] => Laptop
                    [price] => 2400
                    [category] => Electronics
                )

            [1] => Array
                (
                    [name] => Phone
                    [price] => 1600
                    [category] => Electronics
                )

        )

)

 

In this example, we use `tap()` to apply filters and transformations to the `$products` collection without modifying the original `$products` variable. This helps keep the code clean and allows you to chain multiple operations on the collection effectively.

 

Conclusion

 

The `tap()` helper function in Laravel provides a clean and concise way to perform operations on a value and return that value. This tutorial covered basic syntax, code examples for array manipulation, Eloquent model manipulation, and a real-world example with Laravel validation. You can leverage `tap()` in various scenarios to enhance the readability and maintainability of your Laravel code.

Author: moses on 04-08-2023
Related Posts
Subscribe to Our Mailing List
Built by codecontent.pro in partnership with Laraveldev.pro
© 2024 Laraveldev.pro