Untitled

mail@pastecode.io avatarunknown
plain_text
19 days ago
2.8 kB
1
Indexable
Never
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [

            'title' => 'required|string|max:191',
            'image' => 'nullable',
            // 'datetime' => 'required|date',
            // 'status' => 'required|numeric|digits_between:0,11',

        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json(['result' => 'error', 'message' => $validator->errors()->all()]);
            } else {
                return back()->withErrors($validator)->withInput();
            }
        }

        $url_to_img = $this->storeBase64($request->image);

        $live_quiz = LiveQuiz::find($id);
        $live_quiz->title = $request->title;
        $live_quiz->image = $url_to_img;
        $live_quiz->save();

        // if ($request->hasFile('image')) {
        //     $image = $request->file('image');
        //     $imageName = time() . '.' . $image->getClientOriginalExtension();
        //     $imagePath = 'public/uploads/images/live_quizzes/';
        //     \Image::make($image)->resize(300, 300)->save(base_path($imagePath) . $imageName);
        //     $live_quiz->image = $imagePath . $imageName;
        // }


        if (!$request->ajax()) {
            return redirect()->route('live_quizzes.questions.index', $id)->with('success', _lang('Live quiz updated sucessfully!'));
        } else {
            return response()->json(['result' => 'success', 'action' => 'update', 'message' => _lang('Live quiz updated sucessfully!')]);
        }
    }

    public function storeBase64($imageUrl)
    {
        $image_name = rand(100000, 999999) . uniqid() . '.jpg';
        $destination = 'public/uploads/images/live_quizzes/' . $image_name;

        $imageData = file_get_contents($imageUrl);
        $sourceImage = imagecreatefromstring($imageData);

        if ($sourceImage !== false) {
            $width = imagesx($sourceImage);
            $height = imagesy($sourceImage);
            $newWidth = 300; // Replace with the desired width of the new image
            $newHeight = 300; // Replace with the desired height of the new image

            $newImage = imagecreatetruecolor($newWidth, $newHeight);
            imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

            imagejpeg($newImage, $destination, 90); // Save the new image as JPEG with 90% quality

            imagedestroy($newImage);
            imagedestroy($sourceImage);
        }

        return $destination;
    }