Laravel tap() : Eloquent Update and Return Record Example

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 and laravel 9 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 AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsPost;

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….medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:auto!important;margin-right:auto!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

Leave a Comment