Laravel PostgreSQL Issue on updateOrCreateGroup - database

when I use updateOrCreate method on MySQL it's working fine on both conditions create or update. but when I use in PostgreSQL it's update is fine but when creates, show this error:
"SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "group_id" violates not-null constraint DETAIL: Failing row contains (null, aaa, 2020-06-24 17:14:54, 2020-06-24 17:14:54). (SQL: insert into "groups" ("group_id", "title", "updated_at", "created_at") values (?, aaa, 2020-06-24 17:14:54, 2020-06-24 17:14:54) returning "group_id")"
my code:
protected $primaryKey = 'group_id';
protected $guarded = [''];
public $incrementing = true;
public function updateOrCreateGroup($data, $id)
{
return $this::updateOrCreate(
['group_id' => $id],
$data
);
}

Related

Delete on cascade in Model Laravel with eloquent

I want to delete data through the api but it is showing an error because it is necessary to delete records in the properties table.
SQLSTATE[23000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] The DELETE statement conflicted with the REFERENCE constraint "FK_Interests_Properties_User". The conflict occurred in database "CADASTRO", table "dbo.Interests_Properties", column 'interests_user_id'. (SQL: delete from [Interests_User] where [user_id] = 1515626)
I created the model that performs actions on the Interests_Properts table, but when I try to delete the data that has the same interests_user_id, errors are occurring.
InterestsUser.php:
use App\Source\InterestsProperties;
class InterestsUser extends Model
{
protected $connection = 'sql_cadastro';
protected $table = 'Interests_User';
protected $primaryKey = 'id';
public $timestamps = false;
public function properties()
{
$this->belongsToMany(InterestsProperties::class, 'foreign_key');
}
public static function lgpdInterestsUser($id_user, $action)
{
if ($action == 'search') {
$data = InterestsUser::where('user_id', $id_user)->get();
if (count($data) > 0) {
return $data;
} else {
return false;
}
} elseif ($action == 'delete') {
$data = InterestsUser::with('properties')->where('user_id', $id_user)->get();
foreach ($data->properties as $p) $p->delete();
if ($data > 0) {
return 'Success Remove.';
} else {
return 'Not Found.';
}
} else {
return "Action Incorrect!";
}
}
}
InterestsProperties.php
class InterestsProperties extends Model
{
protected $table = 'Interests_Properties';
protected $primaryKey = 'id';
public $timestamps = false;
}
The error is occurring when trying to remove with cascade:
Call to undefined method Illuminate\Database\Eloquent\Builder::foreign()
Table Structure
Interests_User
id
interest_id
user_id
created_at
updated_at
Interests_Properties
id
interests_user_id
key
value
created_at
updated_at
At DB level, using onDelete: when migrating your InterestsProperties model you'll have a line like
$table->foreignId('foreign_key')
to that add ->onDelete('cascade')
after that update each time you delete a record from the main table it will do it in this one to.
At PHP level,
$data = InterestsUser::with('properties')->where('user_id', $id_user)->first();
foreach($data->properties as $p) $p->delete();
PD: Those will remove the property record too.

SQLSTATE[23502]: Not null violation: 7 ERROR - laravel

Below given is an API to upload files.
it shows error -
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"Userid\" of relation \"files\" violates not-null constraint\nDETAIL: Failing row contains (7, null, Distance Learning Promo.mp4, null, null, null, 2021-07-07 13:38:07, 2021-07-07 13:38:07). (SQL: insert into \"files\" (\"FileName\", \"updated_at\", \"created_at\") values (Distance Learning Promo.mp4, 2021-07-07 13:38:07, 2021-07-07 13:38:07) returning \"id\") .
And Postman shows the status 500 internal status error.
I don't think my Userid column here is null . Pls help me with some suggestions
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Uploads;
use Illuminate\Support\Facades\Auth;
class UploadController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function upload(Request $request)
{
$file=$request->file('file_name');
$fileName=$file->getClientOriginalName();
$folder = uniqid().'-'.now()->timestamp;
$file->storeAs('public/other-document/'.$folder, $fileName);
$filePath = $folder.'/'.$fileName;
$dataToInsert = array();
$dataToInsert['FileName'] = $fileName;
$dataToInsert['FilePath'] = $filePath;
if($request->has('uploadType'))
{
$dataToInsert['FileType'] = $request->uploadType;
}
$dataToInsert['uploadedBy'] = Auth::user()->id;
$dataToInsert['Userid'] = $request->bearerToken();
Uploads::create($dataToInsert);
}
}
Migration file
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('Userid');
$table->string('FileName');
$table->string('FilePath');
$table->string('FileType');
$table->integer('uploadedBy');
$table->timestamps();
});
$dataToInsert['Userid'] = $request->bearerToken(); // error is here
if(!$dataToInsert['Userid']){
return "Null value in userID";
}
Check the $dataToInsert['Userid'] holds any value.
Also make Sure that Your are Passing bearerToken in header

SQLSTATE[23502]: Not null violation: 7 Laravel API error

Below is an API to upload files, and it displays the following error.
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "Userid" of relation "files" violates not-null constraint\nDETAIL: Failing row contains (7, null, Distance Learning Promo.mp4, null, null, null, 2021-07-07 13:38:07, 2021-07-07 13:38:07). (SQL: insert into "files" ("FileName", "updated_at", "created_at") values (Distance Learning Promo.mp4, 2021-07-07 13:38:07, 2021-07-07 13:38:07) returning "id")
Also, Postman shows the status 500 internal status error. I don't think my Userid column here is null. Even if Userid column is inserted a dummy value like this: $dataToInsert['Userid'] =1. Also, it shows the same error.
Controller
class UploadController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function upload(Request $request)
{
$file = $request->file('file_name');
$fileName = $file->getClientOriginalName();
$folder = uniqid() . '-' . now()->timestamp;
$file->storeAs('public/other-document/' . $folder, $fileName);
$filePath = $folder . '/' . $fileName;
$dataToInsert = array();
$dataToInsert['FileName'] = $fileName;
$dataToInsert['FilePath'] = $filePath;
if ($request->has('uploadType')) {
$dataToInsert['FileType'] = $request->uploadType;
}
$dataToInsert['uploadedBy'] = Auth::user()->id;
$dataToInsert['Userid'] = $request->bearerToken();
Uploads::create($dataToInsert);
}
}
Migration
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('Userid');
$table->string('FileName');
$table->string('FilePath');
$table->string('FileType');
$table->integer('uploadedBy');
$table->timestamps();
});
I am so sorry. I can't write comments yet. But did you add fields to Model fillable array?
I had a similar problem. And that was because i didn't add that field to fillable array of Model.

function setDataSource() in the AppModel

I use this syntax in the AppModel
public function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $ds);
$this->setDataSource('new_db');
}
The problem is that when this function is called,
Database Error
Error: SQLSTATE[42P01]: Undefined table: 7 ERROR:
missing FROM-clause entry for table "Aco" LINE 1: ...AND "Permission"."aco_id" IN (3, 2, 1) ORDER BY "Aco"."lft... ^
I think this error appears due to the fact that the component ACL is linked to a database which is the default.

cakephp auth and user register stopped working

I have following piece of code:
public function check()
{
$result = $this->User->field('id', array('username' => 'alek#lol.pl'));
debug($result);
}
In my users table I have record:
NSERT INTO `users` (`id`, `username`, `password`, `role`, `created`, `modified`) VALUES
('5', 'alek#lol.pl', '64c918dd65b67b455248c2498bcc5421a66b68a6', 'member', '2012-04-24 10:56:37', '2012-04-24 10:56:37');
and the result of this controller method check is:
false
And the sql query is:
Nr Query Error Affected Num. rows Took (ms)
1 SELECT `User`.`id` FROM `freebooks`.`users` AS `User` WHERE `username` = 'alek#lol.pl' LIMIT 1 1 1 0
So SQL return one row but in cake result is 'false' - whats wrong? something broken??
when I execute this SQL statement in my PhpMyAdmin it correctly returns id = 5
And when I change one line to
$result = $this->User->find('all');
this prints
true
This is impossible!!!
$this->User->field('id', array('username', $this->request->data['User']['username']));
you can check like this:
if(!empty($this->User->field('id', array('username', $this->request->data['User']['username']));)) {
// code
}
OR
$id = $this->User->field('id', array('username', $this->request->data['User']['username']));
$this->User->id = $id;
if($this->User->exists()) {
// code
}

Resources