ItSolutionStuff.com

Laravel Get File Content from Request Object

By Hardik Savani December 2, 2024
Laravel

In this post, I will give you solutio how to get file content from POST request object in laravel application.

Laravel's `Request` class provides the `path()` function to retrieve the real path of a selected file. Using this path, you can access the file's content.

In this example, I demonstrate how to work with a JSON file by selecting it and then retrieving its content from the request object. I'll show you two approaches to fetch the file content. Let's dive into the example:

Example 1:

demo.json

{ "id": "1", "name": "Hardik Savani", "email": "hardik@gmail.com" }

Controller File Code:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class FileController extends Controller { /** * Write code on Method * * @return response() */ public function upload(Request $request) { $request->validate([ "file" => "required" ]); $data = file_get_contents($request->file->path()); dd($data); } } 

Output:

{ "id": "1", "name": "Hardik Savani", "email": "hardik@gmail.com" }

Example 2:

demo.json

{ "id": "1", "name": "Hardik Savani", "email": "hardik@gmail.com" }

Controller File Code:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use File; class FileController extends Controller { /** * Write code on Method * * @return response() */ public function upload(Request $request) { $request->validate([ "file" => "required" ]); $data = File::get($request->file->path()); dd($data); } } 

Output:

{ "id": "1", "name": "Hardik Savani", "email": "hardik@gmail.com" }

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