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
Related
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.
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.
In this code, I would like to get time when the user joined and left and store it to DB. What happens it that I get the same value in both 'joined' and 'left' tables. How to fix it so it would store different values?
Schema::create('user_info', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('ip');
$table->string('joined');
$table->string('left');
});
in LoginController
public function logout() {
$left = now();
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
in Model
protected $fillable = ['ip','name', 'joined'];
const CREATED_AT = 'joined';
const UPDATED_AT = 'left';
public static function storeUser() {
UserInfo::create([
'ip' => Request::ip(),
'name' => Auth::user()->name,
'joined' => now(),
]);
}
BroadcastServiceProvider.php
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('name')) {
UserInfo::storeUser();
session()->put('name',$user->name);
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time,
];
}
});
This image illustates the behaviour after some changes you'll see below. It show that data with key 'left' for now goes not to the intended user but to the first user with this name.
The follow up of this question is here How to override this code so that it insert data properly?
CREATED_AT and UPDATED_AT are timestamps that gets changed by the Eloquent model, whenever a model gets created it's also modified or updated from a non-existing to existing so this is why you get the same value
In the logout function, update the user's left column
public function logout() {
$user_id = auth()->id(); // Get authenticated user ID
$user_info = App\UserInfo::find($user_id); // Get user info
$user_info->left = now(); // Change here
$user_info->save(); // Update here
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
According to your table, there's no way to distinguish between users and their info since the name is not unique
Make a user_id based relationship
User model
public function info()
{
return $this->hasOne(UserInfo::class);
}
UserInfo model
public function user()
{
return $this->belongsTo(User::class);
}
And in the user_infos migration
Schema::create('user_infos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('name');
$table->string('ip');
$table->dateTime('joined');
$table->dateTime('left');
});
Cleaner Method
public function logout() {
$info = auth()->user()->info; // Get user info
$info->left = now(); // Change here
$info->save(); // Update here
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
Hope this helps
I;m using laravel and vue if that makes any difference. The data input I'm using if coming from an excel file, i can see the array of data when i inspect the website so i know the information is there, I'm trying to insert that info into the users table to do a massive user import option.
Basically how I'm doing it is, I'm receiving an excel that gets turned into an array, i separate that array into smaller arrays with only 5 users inside, and iterating thru those and saving that into the users table. The excel is full of info and there isn't anything that is empty.
My store method on the ImportUserController
public function store(Request $request)
{
ini_set('max_execution_time', 300);
$users = $request->all();
try {
DB::beginTransaction();
foreach ($users as $user) {
$dbUser = $this->getUser($user['id']);
Log::error($dbUser);
$dbUser->name = $user['NAME'];
$dbUser->user_name = $user['USERNAME'];
$dbUser->email = $user['EMAIL'];
$dbUser->last_name = $user['LAST-NAME'];
$dbUser->password = $user['PASSWORD'];
$this->isSet('USER-TYPE-ID', $user);
$user_type_id = $this->getUserId($user['USER-TYPE-ID']);
$dbUser->user_type_id = $user_type_id->id;
$dbUser-> save();
}
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new HttpException(500, 'Sucedio un error importando la información favor intentar de nuevo');
}
}
private function isSet($field, $reqData)
{
if (!isset($reqData[$field])) {
throw new HttpException(500, "Sucedio un error importando la información. No se encuenta la columna $field");
}
}
private function getUserId($name)
{
$userId = UserType::where('name', $name)->first();
if (empty($userId)) {
$userId = new UserType();
$userId->name = $name;
$userId->save();
}
return $userId;
}
private function getUser($id)
{
$user = User::where('id', $id)->first();
if (empty($user)) {
$user = new User();
}
return $user;
}
this is the create users file
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_name')->unique();
$table->string('email')->unique();
$table->string('last_name');
$table->string('password', 60);
$table->integer('user_type_id')->unsigned();
$table->foreign('user_type_id')->references('id')->on('user_types');
$table->rememberToken();
$table->timestamps();
});
I'm not sure where the null is coming from? or why this is producing this error.
first print all of your input values then check that ,all values are coming correctly
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.