Tanvir Ahmed
Tanvir Ahmed

Reputation: 1019

How to solve the problem of saving image in laravel

I am trying to save my image into database, it was moving into public folder but it doesnot saving into database. But while except image everything is working fine. And when save() method is called it gives me below error.See the image for more information .

Here what i have tried my code in controller

$student=new Student;
        $student->name = $request->input('name');
        $student->username = $request->input('username');
        $student->email = $request->input('email');
        $student->password = bcrypt($request->input('password'));
        $student->gender = $request->input('gender');
        $student->phone = $request->input('phone');
        if($request->hasFile('image'))
        {
            $file=$request->File('image');
            $ext=$file->getClientOriginalExtension();
            $filename=$student->username . '.' . $ext;
            $file->move('images/',$filename);
            $student->image=$filename;
        }
        $student->save();
        $student->subjects()->attach($request->id);
        return back()->with('msg','Succesfully Added');

Upvotes: 2

Views: 1952

Answers (2)

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

1) Make sure you have added enctype="multipart/form-data" in your form and a with field name="image"

2) In your controller

if( $request->hasFile('image')) {
    $image = $request->file('image');
    $path = public_path(). '/images/';
    $filename = $student->username . '.' . $image->getClientOriginalExtension();
    $image->move($path, $filename);
    $student->image=$filename;
}
    $student->save();

Upvotes: 1

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

use clientExtension() instead of getClientOriginalExtension() and make sure your path is correct here I defined the path of public.

if ($request->hasFile('image')) {
    $file = $request->image;
    $destinationPath = public_path().'/images/';
    $filename= $student->username . '.'.$file->clientExtension();
    $file->move($destinationPath, $filename);
    $student->image=$filename;

}

Upvotes: 3

Related Questions