Laravel Get File Content from Request Object
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...
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
- Laravel Breeze Login with Google Auth Example
- Laravel Datatables Relationship with Filter Column Example
- Laravel Datatables Date Format with created_at Example
- Laravel Eloquent Find with Trashed Record Example
- How to Read JSON File in Laravel?
- How to Set Custom Redirect URL After Login in Laravel Jetstream?
- Laravel Notify Flash Messages using Laravel Notify Example
- Laravel Relationship with Comma Separated Values Example
- Laravel Relationship with JSON Column Example
- Laravel 11 Display Image from Storage Folder Example
- Customize Laravel Jetstream Registration and Login Example
- Laravel 11 One to Many Eloquent Relationship Tutorial