Home » Php » php – Convert image to base 64 string with Laravel

php – Convert image to base 64 string with Laravel

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to convert an image to base 64 with Laravel. I get the image from a form .
I tried this in my controller:

public function newEvent(Request $request){
    $parametre =$request->all();

    if ($request->hasFile('image')) {
        if($request->file('image')->isValid()) {
            try {
                $file = $request->file('image');
                $image = base64_encode($file);
                echo $image;


            } catch (FileNotFoundException $e) {
                echo "catch";

            }
        }
    }

I get this only:

L3RtcC9waHBya0NqQlQ=

How to&Answers:

Laravel’s $request->file() doesn’t return the actual file content. It returns an instance of the UploadedFile-class.

You need to load the actual file to be able to convert it:

$image = base64_encode(file_get_contents($request->file('image')->pat‌​h()));

Answer:

It worked for me in the following way:

$image = base64_encode(file_get_contents($request->file('image')));

I eliminated this part ->pat‌​h();