Write Cleaner Code With Laravel Tap Helper Function

Kumar Ravi
1 min readFeb 23, 2023

--

Laravel tap helper function provides you with a way of writing more cleaner and one-liner code.

Let's see with an example. Let’s say you need to write a function to save data into laravel Cache and access it later.
One way of doing this is like this

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;


class UserController extends Controller
{

public function saveUserName($name){
Cache::set('name',$name);
}

public function getUserName(){

$userName = Cache::get('name');
Cache:forget('name');
return $userName;
}

}

Here in the first function, we are setting the user name; in the second function, we are getting that user name from the cache.
Let's write using it with the Tap helper function

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;


class UserController extends Controller
{

public function saveUserName($name){
Cache::set('name',$name);
}

public function getUserName(){

return tap(Cache::get('name'), fn()=> Cache::forget('name'));
}

}

Let's talk about the tap helper function, It has two parts one is the callback and the second part is the function it executes on that callback.

--

--

Kumar Ravi
Kumar Ravi

Written by Kumar Ravi

entrepreneur by heart developer by profession

No responses yet