Home > Software design >  Call to a member function getRealPath() on string while sending an email
Call to a member function getRealPath() on string while sending an email

Time:02-03

Call to a member function getRealPath() on string error occurs while sending an email.

Controller

public function store(CareerRequest $request)
{
    $requestData = $request->all();

    $filenameWithExt = $request->file('resume')->getClientOriginalName();
    $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
    $extension = $request->file('resume')->getClientOriginalExtension();
    $fileNameToStore = $filename.'_'.time().'.'.$extension;
    $request->file('resume')->storeAs('candidateResume', $fileNameToStore);    
    $requestData["resume"] =$fileNameToStore ;

    Career::create($requestData);

    return redirect()->back();
}

Mailable

class CareerMail extends Mailable
{
    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function build()
    {
        return $this->subject('Career - '. $this->data->subject)

                    ->view('emails.career')
                    ->attach($this->data['resume']->getRealPath(),
                [
                    'as' => $this->data['resume']->getClientOriginalName(),
                    'mime' => $this->data['resume']->getClientMimeType(),
                ]);
    }
}

Error on line

->attach($this->data['resume']->getRealPath(),

CodePudding user response:

Before attaching the file to the email, retrieve it using the Storage facade.

public function build()
{
    $file = Storage::disk('local')->get($this->data['resume']);
    
    return $this->subject('Career - '.$this->data->subject)
        ->view('emails.career')
        ->attachData($file, $this->data['resume']->getClientOriginalName(), [
            'as' => $this->data['resume']->getClientOriginalName(),
            'mime' => $this->data['resume']->getClientMimeType(),
        ]);
}

CodePudding user response:

You are trying to use function getRealPath() on your $fileNameToStore, which is a string : $filename.'_'.time().'.'.$extension.

getRealPath() will only work on $request()->file('resume')->getRealPath().

If you want to get the information of your file, you should use Uploaded file instance instead or get the file instance you stored.

  • Related