I just want to save my image or file in the database as a URL that can easily get for the frontend. I tried it a lot but did not get a solution if anyone can get me out with this?
public function addPPQuestion(Request $pp_questions)
{
$validate = Validator::make($pp_questions->all(), [
'qual_cat_id' => 'required|exists:qualification_categories,qual_cat_id',
'year_id' => 'required|exists:years,year_id',
'course_id' => 'required|exists:courses,course_id',
'board_id' => 'required|exists:board_of__edus,board_id',
'paper' => 'required|mimes:pdf|max:2048',
]);
if ($validate->fails()) {
$messages = $validate->errors()->count() > 1 ? $validate->errors()->all() : $validate->errors()->first();
return response()->json(['code' => 400, 'message' => $messages], 400);
} else {
$paper = $pp_questions->paper;
$fileName = $paper->getClientOriginalName();
$pp_question = pp_question_answer::create([
'paper' => $pp_questions->paper->storeAs('', $fileName, ''),
'qual_cat_id' => $pp_questions->input('qual_cat_id'),
'year_id' => $pp_questions->input('year_id'),
'course_id' => $pp_questions->input('course_id'),
'board_id' => $pp_questions->input('board_id'),
]);
return response()->json(['code' => 201, 'message' => 'Question Created Successfully',
'object' => $pp_question], 201);
}
}
CodePudding user response:
Step 1: Validate the files as you want in the api.
Content-Type: application/json
It will return JSON data as result.
$request->validate(['file' => 'required|mimes:jpeg,jpg,png,gif,svg,pdf,txt,doc,docx,application/octet-stream,audio/mpeg,mpga,mp3,wav|max:204800']);
Step 2: Make a file name & store it in the folder and get the URL of it.
$unique_id = strtolower(str_replace('.', '', uniqid('', true)) . time());
$photoFile = $request->file('paper');
$extension = $photoFile->getClientOriginalExtension();
$fileNameToStore = $unique_id . '.' . $extension;
$filepath = $photoFile->storeAs('photos', $fileNameToStore);
$pp_question = Model::create([
'paper' => $filepath,
'qual_cat_id' => $pp_questions->input('qual_cat_id'),
'year_id' => $pp_questions->input('year_id'),
'course_id' => $pp_questions->input('course_id'),
'board_id' => $pp_questions->input('board_id'),
]);
return response()->json([
'code' => 201,
'message' => 'Question Created Successfully',
'object' => $pp_question
], 201);
Step 3: To display data on the front-end side.
$imagePath = !empty($pp_question->pdf) && Storage::exists($pp_question->pdf) ? Storage::url($pp_question->pdf) : asset(Storage::url('default/pdf.png');