rafalrozek
rafalrozek

Reputation: 133

codeigniter 4, update model

I connected my codeigniter app with mysql. I created a table model like that:

<?php namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model{

    protected $table = 'I_user';
    protected $allowedFields = ['email', 'password','active', 'hash'];

}

And now in my Controller, I want to update user by changing email for example. How to do that? My controller:

<?php namespace App\Controllers;

use App\Models\UserModel;

class Confirm extends BaseController 
{
    public function index($email, $hash)
    {
        if(!isset($email) || !isset($hash)){
            return redirect()->to('/');
        }

        $model = new UserModel();
        $user = $model->where('email', $email)->first();
        if($user['hash'] == $hash){
            // update $user email..
            ??
        }


    }


}

Upvotes: 1

Views: 5089

Answers (3)

K Mandal
K Mandal

Reputation: 1

If the Primary key is not "id" in your data-table, then you need to mention that in your Model.

protected $primaryKey = 'email';

Then use:

$model->update(['email'=> $user['email']], ['email' => '[email protected]']);

Upvotes: 0

Murad Ali
Murad Ali

Reputation: 418

You can do it in such way:

$model->where('email', $user['email'])->set(['email' => 'YourNewEmailAddress'])->update();

or

$model->update(['email'=> $user['email']], ['email' => 'YourNewEmailAddress']);

Upvotes: 4

user13434202
user13434202

Reputation:

You could use update directly to the model data

$data = [
    'email' => 'Yourupdatedemailhere'
];

$model->update($user['email'], $data);

Upvotes: 0

Related Questions