Update a mysql database field with empty value in laravel
Below code explains how to update a db field with null value using Laravel create a database called tbl_employee with few fields as follows.for creating the table you can use the below sql statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
CREATE TABLE IF NOT EXISTS `tbl_employee` ( `id` int(10) NOT NULL, `name` varchar(200) NOT NULL, `age` int(10) NOT NULL, `email` varchar(100) NOT NULL, `phone` int(10) NOT NULL, `country` varchar(200) NOT NULL, `state` varchar(200) NOT NULL, `city` varchar(200) NOT NULL, `empid` int(10) NOT NULL, ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; INSERT INTO `tbl_employee` (`id`, `name`, `age`, `email`, `phone`, `country`, `state`, `city`,`empid`) VALUES (1, 'vasanthan', 34, 'vasanthanpv@gmail.com', 2147483647, 'india', 'Karnataka', 'mangalore',110), (2, 'robin', 30, 'contact@mydoubts.in', 2147483647, 'india', 'mumbai', 'mumbai',111); |
Created one controller UpdateController and one model called Employee model UpdateController
1 2 3 4 |
$data['fieldValue'] = ""; $data['field'] = 'age'; $data['empid'] = $request->id;// for example 110 Employee::updateEmployeeField($data); |
Model-Employee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Employee extends Model { protected $table = 'tbl_employee'; protected $primaryKey = 'id'; public $timestamps = false; protected $fillable = [ 'name', 'age', 'email', 'phone', 'country', 'state', ]; protected $guarded = []; public static function updateEmployeeField($data) { $updateDetails[$data['field']] = $data['fieldValue']; Employee::where('empid', $data['empid']) ->update($updateDetails); } |