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, 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Convert Number to Words in Laravel?
- How to use Laravel Variable in JQuery?
- Laravel Cashier Stripe Subscription Example Tutorial
- Laravel Redirect to Route from Controller Example
- How to Use Google Translator in Laravel?
- How to Select Specific Columns in Laravel Eloquent Model?
- How to Get Columns Names from Model in Laravel?
- How to Create Model in Laravel using Command?
- Laravel Ajax DELETE Request Example Tutorial
- Laravel Ajax GET Request Example Tutorial
- How to Get Environment Variable in Laravel React JS?
- Laravel React JS Pagination using Vite Example