Laravel tap() : Eloquent Update and Return Record Example

By Hardik Savani June 26, 2023 Category : Laravel

Hi Developer,

In this short guide, we will show you laravel update and return record. Here you will learn laravel tap function. We will use laravel update return value. you will learn laravel eloquent update and return object. Here, Create a basic example of laravel tap example.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.

When you 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 provide tap() helper to return updated object.

You can see the below example with output:

Example:

app/Http/Controllers/PostController.php

<?php

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 = "Demo Updated";

$post->body = "Body Demo Updated";

$post->save();

});

dd($post->toArray());

}

}

Output:

array:7 [

"id" => 2

"title" => "Demo Updated"

"slug" => "dr"

"body" => "Body Demo Updated"

"created_at" => "2022-06-02"

"updated_at" => "2022-08-31T13:01:28.000000Z"

"status" => 0

]

I hope it can help you...

Tags :