Laravel Eloquent Update and Return Object using tap() Helper

Hello artisan,

In this laravel tap example, I will show you laravel update and return record using the tap function. Here you will learn laravel tap function example with source code. I will use laravel update return value with the tap function. You will learn laravel eloquent update and return object with tap function.

In this example, I will create a basic example of laravel tap example. You know that when we create a new record using the eloquent create() method then it returns created value object. However, If you update the record using the eloquent update() method then it does not return the updated value object. But sometimes we need an updated object. So I have one solution to do this. Laravel provides a tap() helper to return the updated object.

Example code:

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = tap(Post::find(2), function($post) {
            $post->title = "This is post title";
            $post->body = "Post body goes here";
            $post->save();
        });
  
        dd($post->toArray());
    }
}

 

Read also: Google Map Point A to Point B Direction Example

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js