John Davidson

Insert image and pdf into mysql - Laravel / PHP

0 comments
Message:


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


My Answer:
> To insert an image and PDF file into a MySQL database using Laravel/PHP, you can follow these steps:

1. First, make sure you have a column in your database table to store the image and PDF file. You can use the `BLOB` data type for this purpose.

2. In your Laravel controller, you can use the `updateOrCreate()` method to insert or update the record in the database. Here's an example code snippet:

php
use App\Models\Info;

public function store(Request $request)
{
$user_id = $request->user_id;

$info = Info::updateOrCreate(
['user_id' => $user_id],
[
'image' => file_get_contents($request->file('image')->path()),
'pdf' => file_get_contents($request->file('pdf')->path())
]
);

return response()->json($info);
}


3. In the above code snippet, we are using the `file_get_contents()` function to read the contents of the image and PDF files and store them in the database.

4. Make sure you have the necessary validation in place to validate the file types and sizes before storing them in the database.

5. Also, don't forget to include the necessary form fields in your HTML form to upload the image and PDF files.

6. Remember to handle file uploads securely and efficiently to prevent any security vulnerabilities.

By following these steps, you should be able to insert an image and PDF file into a MySQL database using Laravel/PHP.

Rate this post

5 of 5 based on 2365 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us