Home > Software engineering >  Insert image and pdf into mysql - Laravel / PHP
Insert image and pdf into mysql - Laravel / PHP

Time:12-03

I want to insert image and pdf into mysql database with updateOrCreate()

I tried this but it returns 1 or 0 instead of actual file ..

$info = Info::updateOrCreate(
        ['user_id' => Auth::id()],

        [
         'image' => $request->hasFile('image') && $request->image->move(public_path('uploads'),$request->full_name.'.'.$request->image->getClientOriginalExtension()),
         'cv' => $request->hasFile('cv') && $request->cv->move(public_path('uploads'),$request->user_id.'.'.$request->cv->getClientOriginalExtension())
        ]
    );

CodePudding user response:

Based on your code, you are assigning the values of image and cv by the result of 'hasFile && move_uploaded_file' which returns true or false (0 or 1). what you should do is if has_file and move_uploaded_file returns true, return the file path location. if not, leave it blank.

$info = Info::updateOrCreate(
['user_id' => Auth::id()],

[
 'image' => $request->hasFile('image') && $request->image->move(public_path('uploads'),$request->full_name.'.'.$request->image->getClientOriginalExtension()) ? public_path('uploads').$request->full_name.'.'.$request->image->getClientOriginalExtension() : "",
 'cv' => $request->hasFile('cv') && $request->cv->move(public_path('uploads'),$request->user_id.'.'.$request->cv->getClientOriginalExtension()) ? public_path('uploads').$request->user_id.'.'.$request->cv->getClientOriginalExtension() : ""
]
);

the code above only returns the string of the file location where you uploaded the file (from move_uploaded_file). if you want to insert it directly to the database, you need a blob/binary column and insert the blob to the database using mysql stmt (prepared statement).

  • Related