Create record with Relation Laravel 5.1 - php

Hi i have the next code for create my records
Institution::create($request->all());
User::create([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password'],
'state' => 1,
'profile_id' => 1,
'institution_id' => Institution::max('id'),
]);
The last attributes for the User thats correct implement so?
The last 3 user attributes , it is correct to do it that way? or is there a better

Using Institution::max('id') creates a race condition. Since the create() static method of Eloquent::Model returns the newly-created model, you can just do:
$institution = Institution::create($request->all());
User::create([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password'],
'state_id' => 1,
'profile_id' => 1,
'institution_id' => $institution->id,
]);
Creating a record with known parent ids is generally fine if your goal is to minimize the number of database queries and you have the ids of the related models.
Another way to do it, though it triggers more update queries, is to use Eloquent's built-in methods for adding related models. For example:
$institution = Institution::create($request->all());
$state = State::find(1);
$profile = Profile::find(1);
$user = new User([
'name' => $request['name'],
'lastname' => $request['lastname'],
'phone' => $request['phone'],
'email' => $request['email'],
'password' => $request['password']
]);
$user->state()->associate($state);
$user->profile()->associate($profile);
$user->profile()->associate($institution);
$user->save();
However, in this situation, since the related models are not already loaded, and you know their ids, there is no need to fetch them only to associate them with the User.

Related

Laravel 8.x - Storing data with Eloquent Relationship

I've got a User model that hasOne Membership model, with a users table and a memberships table (each entry in the memberships table has a foreign key linked to a user_id).
I've made a registration page that lets the user have a 7 days trial period on the membership but I'm having trouble storing the data.
This is the dd() of the data in the registration form:
"_token" => "ckRlMligEyTwu7ssOi4TmesycbsPpVQlrJ4jQaBd"
"username" => "JaneDoe"
"password" => "password"
"password_confirmation" => "password"
"expiration" => "2021-04-30"
Now in my controller I've got the following store() method:
public function store(Request $request) {
// validating
$this->validate($request, [
'username' => ['required', 'max:200'],
'password' => 'required|confirmed',
'expiration' => 'required'
]);
// storing
User::create([
'username' => $request->username,
'password' => Hash::make($request->password),
'expiration' => $request->expiration
]);
}
This won't store anything in the memberships table and I have no idea how to correctly write the store method using the Model's Eloquent Relationships declared.
Thanks for the help.
EDIT:
While trying to make some sense i've modified the store() function, now looks like this:
public function store(Request $request) {
// validating
$this->validate($request, [
'username' => ['required', 'max:200'],
'password' => 'required|confirmed',
'expiration' => 'required'
]);
// storing
User::create([
'username' => $request->username,
'password' => Hash::make($request->password)
])->membership(Membership::create([
'expiration' => $request->expiration
]));
}
Now seems like Laravel doesn't know where to get the user_id of the newly created user, like the error suggests:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `memberships` (`expiration`, `updated_at`, `created_at`)
Your solution is to do:
User::create([
'username' => $request->username,
'password' => Hash::make($request->password)
])->membership()->create([
'expiration' => $request->expiration
]);
Using the relation (membership() not membership as an attribute) will already know the relation key (user_id in this case).
You can see more info about this in the documentation.
Other way of doing same is:
$membership = new Membership([
'expiration' => $request->expiration
]);
User::create([
'username' => $request->username,
'password' => Hash::make($request->password)
])->membership()->save($membership);
More info about save() on the documentation.

Laravel Auth Check For An Organization

when a user tries to register I require them to enter an organization ID, I want that organization ID to be checked against my Organization table and see if it exists. If it exists then register the user and if it fails then return an error message. I've been looking around online and couldn't personally find anything like this. If anybody could help, I'd greatly appreciate it.
I am using Laravel 5.6 with the default auth.
Validator:
return Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'org_id' => 'required|string|max:16',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
User Create:
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'org_id' => $data['org_id'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'is_active' => 1
]);
You're looking for the exists rule of Laravel's Validation:
'org_id' => 'required|string|max:16|exists:organizations,id',
The rule is essentially
exists:{table},{column?}
Where table is required, and column is optional, generally used if the name (in this case org_id) is different from the column you want to compare.
For full details, check the Documentation.

How to give Free Bonus in laravel?

I am runing a bitcoin investment website. I want to give user free bonus of 0.005 points on registration. I have tried following in my registration Controller to fill database table. It works perfectly but after 100 user it creat some type of bug and I get error in user login it says:
But I remove all rows of depostit table all functions work perfectly.
trying to get property of non object
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'under_reference' => $data['reference'],
'password' => bcrypt($data['password']),
'verifyToken' => Str::random(40),
'reference' => Str::random(12),
'status' => $status,
'image' => $image25
]);
$deposit = Deposit::create([
'deposit_number' => date('ymd').Str::random(6).rand(11,99),
'user_id' => $user->id,
'plan_id' => "7",
'percent' => "1",
'time' => "30",
'compound_id' => "2",
'amount' => "0.005",
'status' => "0"
]);

how to get last inserted id in laravel 5.4

I am new to laravel and try to add record in db. record is successfully inserted but now i need to getLast inserted id.
Insert record array here:
User::insert(
[
'first_name' => $data->first_name,
'last_name' => $data->last_name,
'email' => $data->signup_email,
'contact' => $data->signup_contact,
'role_id' => $data->role_id,
'password' => bcrypt($data->password_contact),
'confirm_passsword'=>bcrypt($data->confirmpassword_contact),
'created_at' => date('Y-m-d'),
'updated_at' => date('Y-m-d'),
]
);
Thanks to all for any help.
Just replace "insert" with "insertGetId". Thats it.

Laravel mass assignment not saving fields

I have 2 tables within one function that I'd like to save data to. One is the Users table, and the second one is a Clinic table.
My user's table is currently working correctly, but I'm unsure if it's 'best practice':
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])
->clinic()->create($request->only([
'name' => Str::title('clinic_name'),
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
My problem occurs at the 'name' column of the Clinic table. It just doesn't save it, even though it's in the $fillable array in my Clinic column:
protected $fillable = ['user_id', 'name', 'telephone'', 'address_1',
'address_2', 'city', 'postcode'];
I have attempted to 'Chain' the methods together, as I want to save the 'user_id' within the Clinic table because they're related.
Many thanks for your help.
You're overriding the name key in your $request->only() call:
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])->clinic()->create($request->only([
'name' => Str::title('clinic_name'), // This is overriding your 'name' field.
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));
If you want to run Str::title() over the requests clinic_name, you'll need to assign the attributes manually like so:
$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])->clinic()->create([
'name' => Str::title($request->get('clinic_name')),
'telephone' => $request->get('telephone'),
'address_1' => $request->get('address_1'),
'address_2' => $request->get('address_2'),
'city' => $request->get('city'),
'postcode' => $request->get('postcode'),
]);
Note: Just as a tip, you can also just retrieve request input as a property like so:
->create([
'name' => $request->name // Performs $request->get('name').
])
You can't have 'name' => Str::title('clinic_name') when using create(), it must be a single key as 'name'.
You can use the following before creating the user:
$request->replace('name' => Str::title('clinic_name'));

Categories