Convert image to base 64 string with Laravel

Pondikpa Tchabao picture Pondikpa Tchabao · Sep 13, 2017 · Viewed 30k times · Source

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=

Answer

Magnus Eriksson picture Magnus Eriksson · Sep 13, 2017

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()));