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

We Are Recommending You

Laravel Breeze Login with Google Auth Example

Read Now →

Laravel Datatables Relationship with Filter Column Example

Read Now →

Laravel Datatables Date Format with created_at Example

Read Now →

Laravel Eloquent Find with Trashed Record Example

Read Now →

How to Read JSON File in Laravel?

Read Now →

How to Set Custom Redirect URL After Login in Laravel Jetstream?

Read Now →

Laravel Notify Flash Messages using Laravel Notify Example

Read Now →

Laravel Relationship with Comma Separated Values Example

Read Now →

Laravel Relationship with JSON Column Example

Read Now →

Laravel 11 Display Image from Storage Folder Example

Read Now →

Customize Laravel Jetstream Registration and Login Example

Read Now →

Laravel 11 One to Many Eloquent Relationship Tutorial

Read Now →