I don't know what is wrong my code,please help I am almost finish it. I am using Laravel 7 btw
I received this message when I wanna update the phone number/email/password
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email' cannot be null (SQL:
update `users` set `email` = ?, `password` =
$2y$10$KZBGY4BFJIWzgh2wGhQ3yuZivuzo..MOLs2ahAYbXpecOUZsZ/nvC, `users`.`updated_at` = 2022-01-26
21:46:50 where `id` = 7)
Here is my update function
public function updateStaffDetails(Request $request, Staff $staff, User $user)
{
//$name = $request->input('stud_name');
$staff->update([
'staffPhone' => $request['staffPhone'],
'staffEmail' => $request['staffEmail'],
'staffPassword' => $request['staffPassword'],
]);
$user =Auth::user();
$user->update([
//'name' => $staff->staffName,
'email' => $staff->staffEmail,
'password'=> Hash::make($staff->staffPassword), //bcrypt($staff->staffPassword)
]);
$staff->user_id = $user->id;
$user->save();
$staff->save();
return redirect()->route('home',Auth::user())
->with('success','Staff details updated successfully.');
}
as you can see the Staff table will be copied to the users table once it is updated but the email from Users table is null...
here is my routes (because I think the problem is my route but i am not sure )
//admin show details
Route::get('/showDetailsAdm', 'StaffController#showDetailsAdm')->name('admins.showDetailsAdm');
//admin update
Route::put('/admins/updateStaffDetails', 'StaffController#updateStaffDetails')->name('admins.updateStaffDetails');
here is the picture of the column Staffs and Users user_id is FK from Users table
tables
Your route must be like
Route::put('users/{user}/staffs/{staff}/update','StaffController#updateStaffDetails')->name('admins.updateStaffDetails');
Then you can get $user and $staff in your controller. Now, $staff isn't null so you can get email from it.
While calling to this route you need to pass user_id and staff_id as shown below:
route('admins.updateStaffDetails', [$user_id, $staff_id] )
Related
i have function in my controller that create a forecast :
public function updateOrCreate(Request $request, $subdomain, $uuid)
{
$fixture = Fixture::where('uuid',$uuid)->firstOrFail();
request()->validate([
'local_team_score' => 'integer|min:0',
'visitor_team_score' => 'integer|min:0',
'winner_team_id' => 'integer|nullable'
]);
if ($fixture->status !== "PENDING"){
return response()->json([
'message' => "You can not add or modify a forecast if the fixture is not pending"
], 403);
}
$winner_team = null;
// local team win
if ($request->local_team_score > $request->visitor_team_score) {
$winner_team = $fixture->localTeam;
}elseif ($request->local_team_score < $request->visitor_team_score){ //visitor win
$winner_team = $fixture->visitorTeam;
}else{ // draw
$winner_team = FixtureTeam::where('team_id',$request->winner_team_id)->first();
}
$user = auth('api')->user();
$platform = Platform::first();
$forecast = Forecast::updateOrCreate([
'user_id' => $user->id,
'fixture_id' => $fixture->id,
'platform_id' => $platform->id
],[
'local_team_score' => $request->local_team_score,
'visitor_team_score' => $request->visitor_team_score,
'winner_team_id' => is_null($winner_team) ? null : $winner_team->team_id
]);
$forecast->load('winnerTeam');
return new ForecastResource($forecast);
}
As you can see i use updateOrCreate methods to add or update a forecast.
The problem is when 2 requests from the same user run at the same time (and no forecast is already created) 2 row are inserted.
Do you have a solution ?
I See that the problem is not new but i could not find a solution https://github.com/laravel/framework/issues/19372
updateOrCreate does 2 steps:
tries to fetch the record
depending on the outcome does an update or a create.
This operation is not atomic, meaning that between step 1 and 2 another process could create the record and you would end up with duplicates (your situation).
To solve your problem you need following:
determine what columns would give the uniqueness of the record and add an unique index (probably compound between user_id, fixture_id, platform_id)
you need to let database handle the upsert (ON DUPLICATE KEY UPDATE in MySQL, ON CONFLICT (...) DO UPDATE SET in Postgres, etc). This can be achieved in Laravel by using the upsert(array $values, $uniqueBy, $update = null) instead of updateOrCreate.
I'm implementing a log-in form by using Zend Framework 2.
I have a "user" table in mysql database: user(user_id INT AUTO_INCREMENT,email-address, password).
The user will input email-address and password.
My web application will call authenticate() method with the identity is email-address, the credential is password.
If the validation success, getIdentity() return the email-address.
But not only the email-address, I want to know the user_id field to use for other query after logged-in.
How can I get more information in my "user" table?
I don't want to query from database twice. (once for authentication, once for user_id).
Do you have any suggestion?
Thanks.
Just authenticate the correct user call the AuthenticationService and the method getStorage with will return you the storage container for the current user. just pass a object or your user entity in this and after calling $this->identity() you should become your custom identity object.
$authService = $this->getServiceManager('Zend\Authentication\AuthenticationService');
if ( // user auth success ) {
$userObject = array(
'foo' => 'bar',
'baz' => 'bas'
);
$authService->getStorage()->write( $userObject );
}
now by calling $this->identity() u get the following output
var_dump( $this->identity() );
//output
array(
'foo' => 'bar',
'baz' => 'bas'
)
Sometime like this
// Set the input credential values (e.g., from a login form)
$authAdapter
->setIdentity('my_username')
->setCredential('my_password')
// Print the result row
print_r($authAdapter->getResultRowObject());
/* Output:
user table
Array
(
[user_id] => 1
[email-address] => my_username
[password] => my_password
)
Also read more manual: http://framework.zend.com/manual/current/en/modules/zend.authentication.adapter.dbtable.html
I have two tables and i need to filter and put those two table data to gridview.i use joined two table like this
$student=new Student;
$marks=new AssimentMarks;
$criteria_st=new CDbCriteria;
$criteria=new CDbCriteria;
$criteria->select = 't.st_id,t.st_name,stu.ass_id,stu.marks_cr1,stu.marks_cr2,stu.marks_cr3,stu.marks_cr4,stu.marks_cr5';
$criteria->join = 'INNER JOIN assiment_marks stu ON stu.st_id=t.st_id';
$criteria->condition = 'stu.ass_id=:ass_id';
$criteria->params = array(':ass_id'=>Yii::app()->session['modelcrite']['ass_id']);
$criteria->addInCondition('t.st_id', $studentid);
return new CActiveDataProvider($student, array('criteria'=>$criteria,));
but in gridviwe only show the student database values.it is show as .how can i pass two models to CActiveDataProvider ?
this is how data shows
http://i.stack.imgur.com/Kogjz.jpg
1) Foreign key in schema
Your assiment table should reference your student table with a foreign key, like this (assuming SQLite):
CREATE TABLE student (
id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE assiment_record(
id INTEGER PRIMARY KEY,
student_id INTEGER,
cr1 INTEGER,
cr2 INTEGER,
cr3 INTEGER,
cr4 INTEGER,
cr5 INTEGER,
FOREIGN KEY( student_id ) REFERENCES student(id) -- FK goes in the CHILD table.
);
2) Generate models with Gii:
student -> models/Student.php
assiment_record -> models/AssimentRecord.php
Gii is smart and guesses your relations:
// AssimentRecord.php looks good! No changes made!
public function relations()
return array(
'student' => array(self::BELONGS_TO, 'Student', 'student_id'),
);
The assiment record BELONGS TO the student.
3) Tweak gii's output (Student.php)
But Gii's is not perfect, and does not know what your intentions are. The current student relation (HAS_MANY) returns an array, but I don't want to deal with the array (because I'm lazy!), so I change it into a HAS_ONE-relation instead:
// Student.php
public function relations()
{
return array(
// Change this: 'assimentRecords' => array(self::HAS_MANY, 'AssimentRecord', 'student_id'),
/* into this: */ 'assimentRecord' => array(self::HAS_ONE, 'AssimentRecord', 'student_id'),
);
}
The student HAS ONE assiment record.
4) Display the grid:
// views/site/index.php (Or wherever.)
$dataProvider = new CActiveDataProvider( 'Student' );
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns' => array(
'id',
'name',
'assimentRecord.cr1',
'assimentRecord.cr2',
'assimentRecord.cr3',
'assimentRecord.cr4',
'assimentRecord.cr5',
)
));
hi all when clicking the link on my page its not carrying the id from the template when going to the view page, so when the sql queries the database it is querying this
SELECT `Field`.`name`
FROM `pra`.`fields` AS `Field`
LEFT JOIN `pra`.`templates` AS `Template` ON (
`Field`.`template_id` = `Template`.`id`)
WHERE `template`.`id` IS NULL
the database says id should be = 2
here is the code for the view function
$fields = $this->Field->find('all',
array('fields'=>array('name','template_id'),
'conditions' => array('template_id' => $this->Auth->user('template.id'))));
$this->set('field', $fields);
updated code, the template_id still equals null
when hardcoded it works correctly, there is a problem with this line $this->Auth->user
You can try with the following code:
$fields = $this->Field->find('all',
array('fields'=>array('name'),
'conditions' => array('Field.template_id' => $this->Auth->user('template_id'))
)
);
$this->set('field', $fields);
Please be sure there must have any template_id value should be there for the current logged in user.
Kindly ask if it not worked for you.
Check the result of the find call, by doing a debug:
debug($fields);
This will show you the returned data from the query. You can add this to the end of your action method.
If the results are empty, double check the values that are stored in the session Auth key. You can do this by dumping out the session with debug($_SESSION) or use the CakePHP DebugKit. The Debug Kit offers you a small toolbar at the top right of the screen and lets you view session information and such.
function view($name){
$this->set('title_for_layout', 'Create Template');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
$fields = $this->Template->Field->find('list',array(
'fields'=> array('name'),
'conditions' => array(
'template_id'=> $name)));
$this->set('field', $fields);
}
it wasn't passing the param's value
I have a model Post -> hasAndBelongsToMany -> Tag
For testing, I created the fixtures for each model, for example, a fixture for the model Post looks like this
class PostFixture extends CakeTestFixture {
var $import = array('model' => 'Post', 'records' => true, 'connection' => 'fixtures');
}
And everything works great for that Model, but when I try to create the fixture for the HABTM relationship, using the same approach doesn’t work:
class PostsTagFixture extends CakeTestFixture {
var $import = array('model' => 'PostTag', 'records' => true, 'connection' => 'fixtures');
}
The SQL generated by CakePHP is the following
CREATE TABLE `service_types_technicals` (
`technical_id` int(20) NOT NULL AUTO_INCREMENT,
`service_type_id` int(20) NOT NULL AUTO_INCREMENT,
`id` varchar(255) NOT NULL, PRIMARY KEY (`id`)) ;
Wich is not correct because the table does not have a field named id.
Then, I tried this:
class PostsTagFixture extends CakeTestFixture {
var $name = 'PostsTag';
var $import = array('table' => 'posts_tags', 'records' => true, 'connection' => 'fixtures');
}
And again, error, but this time the SQL was:
CREATE TABLE `service_types_technicals` (
`technical_id` int(20) NOT NULL AUTO_INCREMENT,
`service_type_id` int(20) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`service_type_id`)) ;
What am I doing wrong? What is the correct way to import fixtures from another database for has and belongs to many relationships?
Thank you!
Mauro Zadunaisky,
as you state that service_types_technicals does not have an id field, I guess that CakePHP automatically deduces a HABTM from service_types to technicals, as both are nouns written in plural (CakePHP convention). If this is not what you had in mind, then you are forced to alter the name of the table to stay within the conventions.
The problem was the missing of the field id in the habtm relation table, it's fixed now