How can I save two models at the same time in Laravel? - php

I want to know how can I save two models which has one relationship in my models. I don't know how to save it but I need the ID for my patient model to assign to my scale model.
Here is my PatientController.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$scales = new Scale;
$patient->name = $request->input('name');
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->save();
return redirect('/patients')->with('success', 'Paciente creado.');
}
I try this code but get error.
DB::transaction(function() use ($patient, $scales) {
$patient = $patient->save(); //Patient Exists First
Patient::find($patient->id)->scales()->save($scales)
});

You could try something like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->name;
$patient->save();
$patient->scale()->create(['patient_id' => $patient->id, 'sd_abc_1_old' => $request->sd_abc_1_old]);
);
return redirect('/patients')->with('success', 'Paciente creado.');
}
If the model uses a hasOne() relation like you said then the code show work, with a bit of modification of course.

public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = Patient::create([
'name' => $request->input('name'),
]);
$scale = Scale::create([
'patient_id' => $patient->id,
'sd_abc_1_old' => $request->sd_abc_1_old,
]);
return redirect('/patients')->with('success', 'Paciente creado.');
}

First create and store base model and referencing it save related model
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->input('name');
$patient->save();
$scales = new Scale;
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->scales()->save($scales);
return redirect('/patients')->with('success', 'Paciente creado.');
}

Related

Alternately login after register in Laravel

ok, I'm trying to login the users after success registration into their panels. the database line built successfully. but alternately user login become successful but once not.
Here is the Request Controller Code:
$request->merge(['phone'=> '09123456789']);
$request->merge(['name' => 'User']);
$request->merge(['password' => 'pass123456789']);
$request->merge(['email' => 'user#email.com']);
$credentials = $request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required',
'email' => 'required',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $credentials['phone'],
'password' => Hash::make($credentials['password'])
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->route('panel');
}
The Model:
protected $fillable = [
'name',
'phone',
'email',
'password',
];
let me know if I didn't describe perfectly
First, I would stop using validation in the controller and use form request validation instead. It's been the standard since Laravel 5.
Try this simplified code using Auth::login() instead:
public function createUser(Request $request)
{
$request->validate([
'name' => 'required|string|max:64',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required|string|max:64',
'email' => 'required|email|max:64',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect()->route('panel');
}

how to make validation on composite unique key

i have three columns in my database ,
i need to make a validation for these columns ,
and to make the tree of them unique.
Validator::make($request->all(),
[
'name' => 'required|min:4|string',
'color'=>'required',
'size_id'=>'required',
]);
i already tried
Validator::make($request->all(),
[
'name' => 'required|min:4|string|unique:products,name,color,size_id',
'color'=>'required|unique:products,color,name,size_id',
'size_id'=>'required|unique:products,size_id,name,color',
]);
and i tried this
$color = $request->input('color');
$size_id = $request->input('size_id');
$name = $request->input('name');
// dd($name);
return
Validator::make($request->all(),
[
'name' => 'required|min:4|string|unique:products,name,'.'NULL'.',color,'.$color.',size_id,'.$size_id,
'description'=>'required|min:4',
'quantity'=>'required|numeric',
'subcategory_id'=> 'required',
'category_id'=> 'required',
'price'=> 'required|numeric',
'color'=>'required|unique:products,color,'.'NULL'.',name,'.$name.',size_id,'.$size_id,
'size_id'=>'required|unique:products,size_id,'.'NULL'.',name,'.$name.',color,'.$color,
'cover'=>'required|image:png,jpg,jpeg',
// 'images'=>'image:png,jpg,jpeg',
'images.
*'=>'image:png,jpg,jpeg',
]);
but it return undefined offset 3 when i check if it fails or not!
thanks
$color = $request->get('color');
$size_id = $request->get('size_id');
$name = $request->get('name');
// dd($name);
return
Validator::make($request->all(),
[
'name' => 'required|min:4|string|unique:products,name,NULL,id,color,'.$color.',size_id,'.$size_id,
'description'=>'required|min:4',
'quantity'=>'required|numeric',
'subcategory_id'=> 'required',
'category_id'=> 'required',
'price'=> 'required|numeric',
'color'=>'required|unique:products,color,NULL,id,name,'.$name.',size_id,'.$size_id,
'size_id'=>'required|unique:products,size_id,NULL,id,name,'.$name.',color,'.$color,
'cover'=>'required|image:png,jpg,jpeg',
// 'images'=>'image:png,jpg,jpeg',
'images.*'=>'image:png,jpg,jpeg',
]);
the code above solved my problem

Laravel validation does not work

I used laravel 5.2 to build my app but suddenly validation doesn't work out on registration`new users
Route::post('/register','userController#store');
my function on validation part for storing users details
public function store(Request $request)
{
$this->validate($request,[
'fname' => 'required|max:50',
'lname' => 'required|max:50',
'email' => 'required|email|unique:users',
'phone' => 'required|unique:users',
'provider' => 'required',
'company' => 'required',
'password' => 'required|min:8',
'IDtype' => 'required',
'IDnumber' => 'required',
'region' => 'required|max:32',
'signature' => 'required'
]);
}
Things were working well but now return
"fname":["validation.required"],"lname":["validation.required"],"email":["validation.required"],"IDtype":["validation.required"],"IDnumber":["validation.required"]} returned as response
`
You shoud use $request->all() instead of $request
public function store(Request $request)
{
$this->validate($request->all(),[
........
]);
}
In Laravel 5.5 you can call the validate method on request and it's recommended
$request->validate($rules);

Query String validation Laravel

I don't know how to get the query string array to validate in Laravel Validation.
here is my code
public function addUserByAdmin(Request $request){
$this->validate($request,[
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
$uesrAction = new UserAction($this->repository);
$user = $uesrAction->addUser($request->input('phone'),$request->input('password'),$request->input('name'),$request->input('fullname'),$request->input('position'));
if($user){
return response()->json(['success' => 'success','user'=>$user]);
}
return response()->json(['success' => 'fail']);
}
but validation doesn't work.Then I tried Validation::make() method and also didn't work.
My URL be like
http://localhost:8000/admin/users/add-user?phone=abcdefg&password=erer&name=ere&fullname=rere&position=343
If you are using laravel 5.5, change your code as follows:
public function addUserByAdmin(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
// ...
}
One of the features that was added in this update is that other way to use the validate() method:
More info:
https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic
https://laravel.com/docs/5.5/releases

Laravel 5.2 Modify Request After Form Validation Before Controller

I'm using laravel 5.2 and i'm using Form Request that given by laravel vendor to make my code clean, so i don't have many code on my controller :
public function store( CouponRequest $request )
{
DB::beginTransaction();
try {
$coupon = Coupon::create( $request->all() );
DB::commit();
return redirect()->route('admin.coupons.index');
} catch (\Exception $e) {
DB::rollback();
return redirect()->back()->withInput();
}
And this is my sample code about my request form :
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
Where should i place this command? :
$start_date = Carbon::create( $request->start_year, $request->start_month, $request->start_day );
$start_date->setTimeFromTimeString( $request->start_time );
$finish_date = Carbon::create( $request->finish_year, $request->finish_month, $request->finish_day );
$finish_date->setTimeFromTimeString( $request->finish_time );
If i place this code before validation, i could be error when some field not filled well by users.
So what i want is to place this code after validation success, but i don't want to place it at my controller.
Is there FormRequest function that can be called after validation success to modify my request??
I think it's not good when there's much code at controller, so i want to minimalize my controller code.
I am going to attempt this using FormRequest. If the intention here is to both validate and assign start_date and finish_date, this is probably the plausible way of doing so in Laravel:
public function rules()
{
switch ( strtolower( $this->method ) ) {
case 'post':
{
return [
'code' => 'required|unique:coupons,code',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
case 'put':
{
return [
'code' => 'required',
'name' => 'required',
'start_year' => 'required',
'start_month' => 'required',
'start_day' => 'required',
'start_time' => 'required',
'finish_year' => 'required',
'finish_month' => 'required',
'finish_day' => 'required',
'finish_time' => 'required',
'using_time' => 'required',
'type' => 'required',
'free_shipment' => 'required',
'target' => 'required',
'target_user' => 'required'
];
}
default:
{
return [];
}
}
}
/**
* #inheritDoc
*
* This method overrides Laravel's defeault FormRequest
* to create validator with `after()` hook
*/
protected function validator($validator)
{
$validator
->make(
$this->validationData(), $this->rules(), $this->messages(), $this->attributes()
)
->after(function($validator) {
if ($date = $this->getCarbonInstanceFromPrefix('start')) {
$request->start_date = $date;
} else {
$validator->errors()
->add('start_year', 'Invalid starting date and time');
}
if ($date = $this->getCarbonInstanceFromPrefix('finish')) {
$request->finish_year = $date;
} else {
$validator->errors()
->add('finish_year', 'Invalid finish date and time');
}
});
}
/**
* Retrieve carbon instance from current request, using prefix
*
* #param string $prefix
*
* #return Carbon|null
*/
protected function getCarbonInstanceFromPrefix($prefix = '')
{
try {
$date = Carbon::create(
$request->get($prefix . '_year'),
$request->get($prefix . '_month'),
$request->get($prefix . '_day')
);
$date->setTimeFromTimeString( $request->get($prefix . '_time') );
return $date;
} catch (\Exception $e) {
return null;
}
}
Quick Explanation
FormRequest essentially extends from Illuminate\Foundation\Http\FormRequest and can override the method where instance of Validator is created. By creating your custom validator, you can attach after() event to both validate each date inputs, and also assign additional parameter to request in one go.

Categories