CodeIgniter Forums
Models insert() and save() methods return "unknown error" but the query builder works - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: Models insert() and save() methods return "unknown error" but the query builder works (/thread-79406.html)



Models insert() and save() methods return "unknown error" but the query builder works - Polymorphism - 06-10-2021

I'm trying to get user creation functionality working on a signup page. When the form is submitted I use either
Code:
$user->insert($data)
or
Code:
$user->save($data)
. When I call
Code:
$user->error()
it returns "Unknown error" with a code of "101".

If I try to insert the same date using the Query Builder then it works correctly.

Am I using the model class incorrectly?

Here is my code for the method:


PHP Code:
public function create()
 {
        $user = new User();

        $rules = [
            'username' => 'required|min_length[2]|alpha_numeric',
            'email' => 'required|valid_email',
            'password' => 'required',
            'password_confirm' => 'required|matches[password]'
        ];

        /**------------------------------------------------------------------------------
        * Validation
        ------------------------------------------------------------------------------*/
        if (! $this->validate($user->validationRules))
        {
            echo view('login/signup', [
                'validation' => $this->validation,
            ]);
        } else
        {
            $username $this->request->getVar('username');
            $email $this->request->getVar('email');
            $password $this->request->getVar('password');

            $userFound $user->where('username'$username)->first();
            $emailFound $user->where('email'$email)->first();

            $data = [
                'username' => $username,
                'email' => $email,
                'password' => password_hash($passwordPASSWORD_DEFAULT)
            ];

            dump($user->insert($data));
            dump($user->error());

            $this->session->setFlashdata("message""An account for <strong>{$username}</strong> has been created. Now you can login!");
            return redirect()->to('/login');
        



RE: Models insert() and save() methods return "unknown error" but the query builder works - paliz - 06-11-2021

look my codes 
PHP Code:
<?php
namespace CoreCommon\Controllers;


use 
CoreCommon\Entities\AdvertisementMediaEntity;

use 
CoreCommon\Libraries\CustomFileSystem;
use 
CoreCommon\Models\AdvertisementMediaModel;
use 
CodeIgniter\HTTP\ResponseInterface;


class 
AdvertisementMedia extends ApiController
{


    /**
    * index function
    * @method : GET
    */
    public function index()
    {

        $advertisementMediaModel = new AdvertisementMediaModel();

        $result $advertisementMediaModel->select($this->urlQueryParam->getFiled())
            ->whereIn($this->urlQueryParam->extractQueryKey('in'), $this->urlQueryParam->extractQueryValue('in'))
            ->whereNotIn($this->urlQueryParam->extractQueryKey('nin'), $this->urlQueryParam->extractQueryValue('nin'))
            ->orWhereIn($this->urlQueryParam->extractQueryKey('oin'), $this->urlQueryParam->extractQueryValue('oin'))
            ->orWhereNotIn($this->urlQueryParam->extractQueryKey('onin'), $this->urlQueryParam->extractQueryValue('onin'))
            ->where($this->urlQueryParam->extractQueryArray('whr'))
            ->orWhere($this->urlQueryParam->extractQueryArray('owr'))
            ->like($this->urlQueryParam->extractQueryArray('lik'))
            ->orLike($this->urlQueryParam->extractQueryArray('olk'))
            ->orderBy($this->urlQueryParam->getSort(), $this->urlQueryParam->getOrder())
            ->paginate($this->urlQueryParam->getLimit(), 'default'$this->urlQueryParam->getPage(), $this->urlQueryParam->getOffset());



        return $this->respond([
            'data' => $result,
            'pager' => $advertisementMediaModel->pager->getDetails()
        ], ResponseInterface::HTTP_OKlang('Common.api.receive'));

    }

    /**
    * show function
    * @method : GET with params ID
    */
    public function show($id null)
    {
        $advertisementMediaModel = new AdvertisementMediaModel();


        return $this->respond([

            'data' => $advertisementMediaModel->where('id'$id)->paginate(1'default'),
            'pager' => $advertisementMediaModel->pager->getDetails()
        ], ResponseInterface::HTTP_OK,  lang('Common.api.receive'));


    }

    /**
    * create function
    * @method : POST
    */
    public function create()

    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $customConfig = new \CoreCommon\Config\CoreCommonConfig();
        $imageService =    \CodeIgniter\Config\Services::image();
        $advertisementMediaEntity = new AdvertisementMediaEntity();


        if ($this->request->getPost()) {

            $rules = [
                'image' => 'uploaded[image]|max_size[image,4096]|ext_in[image,png,jpg,mp4,gif,webp]',

            ];
            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_ACCEPTABLElang('Common.api.validation'));

            }

            $advertisementMediaEntity->advertisement_id $this->request->getPost('advertisement_id');

            if (isset($_FILES['image'])) {

                foreach ($this->request->getFileMultiple('image') as $avatar) {


                    $avatar->move($customConfig->uploadDirectory '/advertisement'time() . '.' $avatar->getClientExtension());


                    $advertisementMediaEntity->path $avatar->getName();
                    $advertisementMediaEntity->editPath($avatar->getExtension() != 'mp4');

                    if (!$advertisementMediaModel->save($advertisementMediaEntity)) {

                        return $this->respond([
                            'error' => $advertisementMediaModel->errors(),
                            'success' => false,
                        ], ResponseInterface::HTTP_BAD_REQUEST,  lang('Common.api.reject'));

                    }
                }


            }


            return $this->respond([
                'data' => ''
            ], ResponseInterface::HTTP_CREATEDlang('Common.api.save'));

        }

    }

    /**
    * update function
    * @method : PUT or PATCH
    */
    public function update($id null)
    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $customConfig = new \CoreCommon\Config\CoreCommonConfig();
        $imageService =    \CodeIgniter\Config\Services::image();
        $handy = new CustomFileSystem();
        $advertisementMediaEntity = new AdvertisementMediaEntity();
        $adsMedia null;

        if ($this->request->getPost()) {

            $rules = [
                'image' => 'uploaded[image]|max_size[image,4096]|ext_in[image,png,webp,jpeg,jpg,mp4,gif]',

            ];

            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false,
                ], ResponseInterface::HTTP_NOT_ACCEPTABLElang('Common.api.validation') );

            }


            $adsMedia $advertisementMediaModel->where('id'$id)->first();

            if (is_null($adsMedia)) {
                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_FOUNDlang('Common.api.exist'));
            }

            $advertisementMediaEntity->id $id;
            $advertisementMediaEntity->advertisement_id $adsMedia->advertisement_id;
            if (isset($_FILES['image'])) {

                foreach ($this->request->getFileMultiple('image') as $avatar) {

                    if ($avatar->getExtension() == 'mp4')
                        $avatar->move($customConfig->uploadDirectory '/advertisement/video'time() . '.' $avatar->getClientExtension());
                    else
                        $avatar->move($customConfig->uploadDirectory '/advertisement/image'time() . '.' $avatar->getClientExtension());

                    $advertisementMediaEntity->path $avatar->getName();

                    $advertisementMediaEntity->editPath($avatar->getExtension() != 'mp4');

                    if (!$advertisementMediaModel->update($id$advertisementMediaEntity)) {

                        return $this->respond([
                            'error' => $advertisementMediaModel->errors(),
                            'success' => false,

                        ], ResponseInterface::HTTP_BAD_REQUEST,  lang('Common.api.reject'));

                    }
                }


            }


            $handy->removeSingleFile(ROOTPATH $adsMedia->path);

            return $this->respond([
                'data' => array(['id' => $id,
                    'advertisement_id' => $adsMedia->advertisement_id,
                    'path' => $advertisementMediaEntity->path])
            ], ResponseInterface::HTTP_OK,  lang('Common.api.update'));
        }

    }

    /**
    * edit function
    * @method : DELETE with params ID
    */
    public function delete($id null)
    {


        $advertisementMediaModel = new AdvertisementMediaModel();
        $handy = new CustomFileSystem();
        $id = ($id == $id);

        if ($id == 0) {

            $isExist $advertisementMediaModel->where(['advertisement_id' => $this->urlQueryParam->getForeignKey()])->
            findAll();
            $target = array('advertisement_id' => $this->urlQueryParam->getForeignKey());
        } else {
            $isExist $advertisementMediaModel->where(['id' => $id])->findAll();
            $target = array('id' => $id);
        }


        if ($isExist) {
            $advertisementMediaModel->where($target)->delete();
            foreach ($isExist as $path) {

                $handy->removeSingleFile(ROOTPATH $path->path);
            }


        }

        return $this->respond([

        ], ResponseInterface::HTTP_OKlang('Common.api.remove'));

    }