Database Relationship - Laravel - php

I am having issues inserting data into my database tables. I have users table which is has a relation of one to many to school table and region table. That is, users table has foreign keys of school and region tables.
I have created the relations correctly but then when i try to insert values into the database, i get the error.
PS: I have one user(admins) in the user table (the school_id and region_id was inserted accurately) already which i saved through RegisterController. Now, when i sign in with the user(admin) already saved, i want to save other users through the UserController but then i get the error above.
What am i not doing right?. I am only a beginner with database relationship and laravel
General error: 1364 Field 'school_id' and `region_id`doesn't have a default value
meaning the field cannot be empty.
UserController
public function store(UserFormRequest $request)
{
$user = new User(array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'password'=> $request->get('password'),
'phone' => $request->get('phone')
));
$user->save();
}

there are three solutions to your problem.
1
public function store(UserFormRequest $request)
{
$user = new User(array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'password'=> $request->get('password'),
'phone' => $request->get('phone'),
'school_id'=>'you must pass value here',
'region_id'=>'you must pass value here'
));
$user->save();
}
2 Go to phpmyadmin make your school_id,region_id default value NULL. so you are good to go.

MySQL is telling you that those fields can't be empty because they aren't nullable.
To make those fields nullable() in your users migration:
// Your create users table migration
$table->integer('school_id')->nullable();
$table->integer('region_id')->nullable();
(You can add any other properties to these - like index(), unsigned(), or foreign keys, etc.)

Related

Laravel 8 unique validation rule doesn't work with user_id

I'm using Laravel 8 and the unique validation rule to ensure that a record remains unique, I'm now trying to extend this so that it's unique per user as well, but when expanding the functionality and using the rule in array form it doesn't seem to validate the user ID and instead gives me a integrity constraint violation.
So I have a table called brands, and this table contains two columns in question: brand and user_id, I need to ensure that when storing a record that the brand is unique against the brand column and that the logged in in user's ID the one making the request, e.g:
Two users can have the same brand, but a single user can't have multiples of the same brand.
$validator = Validator::make($request->all(), [
'brand' => [
'required',
'string',
Rule::unique('brands')->where(function ($query) {
return $query->where('user_id', Auth::id());
})
],
'url' => 'required|string',
'telephone' => 'required|string|min:11|max:11'
]);
I've also tried:
'brand' => 'required|string|unique:brands,brand,user_id,' . Auth::id()
What am I missing?
According to the documentation you have to use the ignore() function:
Rule::unique('users')->ignore($user->id),
on your case:
Rule::unique('brands')->ignore($user->id, 'user_id'),

Eloquent - fields that match in a record if firstOrNew fails with multiple conditions

Suppose I have the following create code
$User = User::firstOrNew(
array(
'username' => $args['username'],
'phone_no' => $args['phone_no']
),
array(
'otherDetails' => 'here',
)
);
$User->save();
if (!$User->wasRecentlyCreated) {
// code to check which field has same record in db
}
After confirming that the insertion was not able to push through because an existing record has been fetched, is there any way I can find out which of either username or phone_no has the same data in the User table? Without using another where lookup in the model. Thanks.

General error: 1364 Field 'department_id' doesn't have a default value

here's the error
SQLSTATE[HY000]: General error: 1364 Field 'department_id' doesn't
have a default value (SQL: insert into ms_user (name, username,
role, email, password, updated_at, created_at)
ms_user model
protected $fillable = [
'department_id','name', 'email', 'password','username','role',
];
create function :
{
return ms_user::create([
'name' => $data['name'],
'username' => $data['username'],
'role' => $data['role'],
'email' => $data['email'],
'department_id' => $data['department_id'],
'password' => bcrypt($data['password'])
]);
}
validator function :
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'username' => 'required|string|max:255',
'role' => 'required|in:user,admin',
'department_id' => 'required|string',
'email' => 'required|string|email|max:255|unique:ms_user',
'password' => 'required|string|min:6|confirmed',
]);
}
department_id is a dropdown menu that contains data from the ms_department table,
department_id becomes the foreign key in the ms_user table and as the primary key in the ms_department
It seam that your are trying to create a user with the filed department_id set to null. In your controller it seams your are passing $data['department_id'] I presume that value comme from the Request Object. But as that field doesn't have any value, when you the code to create user is execute, It send and empty value to that database. The table which contain users data doesn't allow that field to be empty.
You solve that by updating you migration to allow null on the departement_field like this
$table->integer('department_id')->nullable();
Or you can check if $data['department_id'] isn't null but using debug($data) in your controller.
it seems you are trying to make a bulk upload if not the name attribute of the input referring to department_id is empty or not correctly spelled
I had the same issue but the error in my case originated from my controller where I interchanged the names of my field living out exp_date
I had the same problem. I checked the stream on which data is passed in.
Check if everything on view is ok.
Check if everything on controller is fine.
Check if field exists in model .
Check if field exists in migration.
For me, I had put a . dot on my model. Like
protected $fillable = [
'department_id'.'name', 'email', 'password','username','role',
];
between department_id and name.
The spellings are also important. Since there is no data from the view, I can't say for sure - but check if everything is correct.

Is there a common way for updating two joined tables in Laravel?

I'm trying to update two tables in Laravel. But I don't know if you can do this while using an associative array with the help of Object->update($associative-array);
I have made an update sequence in laravel which updates a user and a location in two separate tables with a foreign key in the user table. I tried to update both tables doing update statements with the objects of the tables. I tried this in the following way:
$user->update($attributes);
$user->update($attributes); $location->update($attributes);
But this will only update the user table and skips the location table. The $attributes array contains multiple column data of the table user and location. The array is in order of the first column from the user table to the last column of the location table.
But neither of those tries updated both the tables. They only update user and skips location. As far as I know, is that you can do it this way with an associative array if the array contains the column data in the same order of a table and Laravel does the rest. With only updating the user table it does work, But I want it to work with two tables in the way It works using the update function with the object.
MySQL tables
users:
id
firstname
middlename
lastname
active
email
password
phone
mobile_work
phone_work
gender
position_id
settling_id
location_id
locations:
id
street
house_number
addition
zipcode
city
province
country
public function update(Request $request, User $user, Location $location)
{
$attributes = request()->validate([
'firstname' => 'min:3|max:50',
'middlename' => 'max:50',
'lastname' => 'min:3|max:50',
'active' => 'required',
'email' => 'min:3|max:100',
'gender' => '',
'phone' => 'numeric|min:8',
'mobile_work' => 'numeric|min:8',
'phone_work' => 'numeric|min:8',
'position_id' => '',
'settling_id' => '',
'location_id' => '',
'street' => 'required|min:3',
'house_number' => 'required|numeric',
'addition' => '',
'zipcode' => 'required|min:6|max:7',
'city' => 'required|min:3',
'province' => 'required|min:3',
'country' => '',
]);
$user->update($attributes);
}
If the way I'm trying to do it is impossible, I'd like to hear what the standard approach is in updating two tables within one update sequence.
What you try to do is not quite right. You should try to update the relation as well, and preferably first like
$location->update($locationAttributes);
$user->update($userAttributes);
By the way, it is not quite clear you want to update Location record or you want to associate a new Location to User. If it is latter then you can associate the Location to user like
$user->locations()->attach($locationId);
I made the mistake to not include the locations function from the model User into the update sequence.
User model:
public function locations()
{
return $this->hasOne(Location::class, 'id', 'location_id');
}
I fixed the problem by simply deviding the $attribute array to 2 arrays with their own table column data. I also made a second statement which calls the location function from the model and updates it accordingly.
$user->locations()->update($locationAttributes);
$user->update($attributes);
With $attributes only containing the user information and $locationAttributes only containing the location information.
$locations() refers to the row in the table locations. It knows which row to pick by taking the location_id from the selected user.

Inserting with relationships in laravel

I am facing a problem in Laravel 5.3 that I looked the docs and also searched web but didn't find anything on it.
I am using Laravel Relationships to join two tables. Now I want the data to be inserted on both the tables at the same time after the user submits a form. The catch in this is the first table is the primary one say "users" and second one "xyz" belongsTo the first table. The table "xyz" contains "users_id" column that connects both the tables. And obviously "users_id" is the "id" column of "users" table.
Now the problem arriving is that I want to insert the data in "users" table (that is easily done) and "xyz" table at the same time. The User::create() function will create the user data easily and it is working also but for inserting the data in "xyz" table I will be needing the "user_id" column data and ID will not be generated until the user is created as ID column has Auto-Increment attribute activated.
Code:
$user = new User;
$inputArry = array('data1' => $request['field1'],
'data2' => $request['field2'],
'data3' => $request['field3'],
);
$user->create($inputArry);
$user->xyz()->create([
'user_id' => $user->id,
'name' => $request['name'],
'about' => $request['desc'],
'tag' => $request['tag'],
]);
Above is the code that I am using for this purpose but it is giving me a error.
Error:
QueryException in Connection.php line 761:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'soft_id' cannot be null (SQL: insert into `xyz` (`user_id`, `name`, `about`, `tag`, `updated_at`, `created_at`) values (, John, I am John, dev, 2016-11-09 21:01:29, 2016-11-09 21:01:29))
One way of inserting related table is using relations as:
$user = User::create($user_inputs);
$xyz = $user->xyz()->create($xyz_inputs);
It will automatically fills the user_id in the xyz table.
If you need insert many items, use createMany or saveMany method.
For example:
$post = App\Post::find(1);
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
In the offical laravel docs:
https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models
You can create them like this instead of saving them on same time...
$id = User::create($input_arr)->id;
Xyz::create([
'user_id' => $id,
...
]);

Categories