ItSolutionStuff.com

Laravel tap() : Eloquent Update and Return Record Example

By Hardik Savani • April 16, 2024
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, laravel 10 and laravel 11 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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Convert Number to Words in Laravel?

Read Now →

How to use Laravel Variable in JQuery?

Read Now →

Laravel Cashier Stripe Subscription Example Tutorial

Read Now →

Laravel Redirect to Route from Controller Example

Read Now →

How to Use Google Translator in Laravel?

Read Now →

How to Select Specific Columns in Laravel Eloquent Model?

Read Now →

How to Get Columns Names from Model in Laravel?

Read Now →

How to Create Model in Laravel using Command?

Read Now →

Laravel Ajax DELETE Request Example Tutorial

Read Now →

Laravel Ajax GET Request Example Tutorial

Read Now →

How to Get Environment Variable in Laravel React JS?

Read Now →

Laravel React JS Pagination using Vite Example

Read Now →