26

I have a form that sends a text file via POST method in Laravel 4. Inside the Controller, however, I can't figure out how to get its content in order to put it into a BLOB field in the DB.

Laravel's documentation and all the posts I found into the web, always show how to save the content into a file with the ->move() method.

This is my code in the Controller:

$book = Books::find($id);
$file = Input::file('summary'); // get the file user sent via POST
$book->SummaryText = $file->getContent(); <---- this is the method I am searching for...
$book->save(); // save the summary text into the DB

(SummaryText is a MEDIUMTEXT on my DB table).

So, how to get the file content in Laravel 4.1, without having to save it into a file? Is that possible?

4 Answers 4

43

If you're posting a text file to than it should already be on the server. As per the laravel documentation, Input::file returns an object that extends the php class SplFileInfo so this should work:

$book->SummaryText = file_get_contents($file->getRealPath());

I'm not sure if the php method file_get_contents will work in the Laravel framework...if it doesn't try this:

$book->SummaryText = File::get($file->getRealPath());
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, file_get_contents() works under Laravel. I chose your first solution. Thank you very much!
getting error "message: "Call to a member function getRealPath() on string", exception: "Error"..."
17

Since Laravel v5.6.30 you can get the file content of an uploaded file like:

use Illuminate\Http\Request;

Route::post('/upload', function (Request $request) {
    $content = $request->file('photo')->get();
});

source: this commit

1 Comment

Thank you, +1 for pointing out the source code, which was a great help.
6

Nicer solution instead of file_get_contents will be to use the SPL class methods as FileUpload is already extending them.

$file = Input::file('summary')->openFile();
$book->SummaryText = $file->fread($file->getSize());

To read more about SplFileInfo and SplFileObject see:

As those could be really usefull and using SPL which is OOP is nicer solution than structural PHP functions.

1 Comment

What is nicer about it? Does it provide some inherit error checking?
-1
\File::get($directory.$filename);

Worked for my project, where directory and filename are determined by the upload methods. The backslash is used when creating workspaces (packages) in laravel4.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.