I have issue that customer_id comes null when there is no data in the table. I know that there is a function IFNULL by using which I can change customer_id null to 0. So here is my query which is not working. checked a lot of related issues solved in the stackover flow but I could not find the solutino for my self if any one can help me with it will be kind of him. it show me this error
"message": "Trying to get property of non-object",
customerController code is
public function store(Request $request)
{
//
try {
$this->validate($request,[
'name'=>'required',
'contact'=>'required|unique:Customers',
// 'contact'=>'required',
'address'=>'required',
'email'=>'required|string|email|max:191|unique:Customers',
]);
$getId = DB::table('Customers')->select('*', DB::raw('ifnull(id,0)'))->first();
$getfirst = $getId->id;
if($getfirst == 0)
{
$getfirst = 1;
$incId = $getfirst;
}
else{
$incId = $getfirst+1;
}
// $lastInsertedId= $Customer->id;
$Customer= Customer::create([
'name'=>$request['name']."-". $incId ,
'contact'=>$request['contact'],
'address'=>$request['address'],
'email'=>$request['email']
]);
return response()->json($Customer);
}
catch (Exception $e) {
return response()->json($e->getMessage(), 500);
}
}
customer table is
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->default("مشتری");
$table->integer('contact')->unique();
$table->string('address');
$table->string('email')->unique();
$table->softDeletes();
$table->timestamps();
});
}
IFNULL
is used to check the field is nullable or not.
So it is not used to check a record exist or not.
You can use empty()
to check the object is exist
$getId = DB::table('Customers')->first();
$getfirst = empty($getId)? 0 : $getId->id;
我想你可以写成:
DB::raw('IFNULL(id, 0)')
尝试这个
$getId = DB::table('Customers')->selectRaw(['*', 'IFNULL(id,0)'])->first();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.