Search code examples
phplaravelbase64encode

Convert image to base 64 string with Laravel


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=


Solution

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