How To Submit Form If The User Don't Want To Add hasMany FormItems - laravel

I'm using Laravel 5.7.*.
I have form which hasMany formItems, Like a form hasMany formItems & formItems belongsTo form, but i want an if between them, that if user don't want to add formItems only form data store in DB and if user want to add formItems both data store in DB, right now, it's storing both data in DB, but i don't how to make it store if user don't want formItems.
Here is my FormController store method():
public function store(Request $request)
{
//SUBMITTING FORM DATA
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_name' => $request['user_name'],
]);
//SUBMITTING FORMITEMS DATA
$form_items = [];
foreach($request['formItems'] as $form_item) {
$form_items[] = new FormItem([
'form_id' => $form->id,
'family_name' => $form_item ['family_name'],
'family_phone' => $form_item ['family_phone'],
]);
}
$form->formItems()->saveMany($form_items);
}
Image For Better Understanding:

you can do this
public function store(Request $request)
{
//SUBMITTING FORM DATA
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_name' => $request['user_name'],
]);
$form_items = [];
foreach($request['formItems'] as $form_item) {
// when the user enter $form_item ['family_name'] && $form_item ['family_phone'] store the FormItem
// or $form_item ['family_name'] || $form_item ['family_phone']
// depending if both are required or not
if($form_item ['family_name'] && $form_item ['family_phone']){
$form_items[] = new FormItem([
'form_id' => $form->id,
'family_name' => $form_item ['family_name'],
'family_phone' => $form_item ['family_phone'],
]);
}
}
$form->formItems()->saveMany($form_items);
}

You could have a checkbox on your form to ask the user if they want to save form items too.
<input type="checkbox" name="save-form-items" value="true" id="save-form-items">
<label for="save-form-items"> Do you want to save form items?</label>
and then in your controller, you can do something like this:
public function store(Request $request)
{
//SUBMITTING FORM DATA
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_name' => $request['user_name'],
]);
if ($request->has('save-form-items')) {
$form_items = [];
foreach($request['formItems'] as $form_item) {
$form_items[] = new FormItem([
'form_id' => $form->id,
'family_name' => $form_item ['family_name'],
'family_phone' => $form_item ['family_phone'],
]);
}
$form->formItems()->saveMany($form_items);
}
}

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

Laravel Livewire Dynamic Form Data Not Working

Quite new to Laravel Livewire. I'm trying to create a dynamic form for application but I couldn't quite understand how to attach additional data when storing.
The user selects the instructor(faculty_id), schoolyear(sy) and semester(sem). And new schedule and option to add more rows()
This is from my controller store() method
public function store()
{
$order = Emp_sched::create([
'faculty_id'=>$this->faculty_id,
'sem'=>$this->sem,
'sy'=>$this->sy,
]);
foreach ($this->createScheds as $sched) {
$order=(['corsdes' => $sched['corsdes']],
['c_time' => $sched['c_time']], ['day' => $sched['day']], ['room' => $sched['room']]);
}
return 'Schedules Saved!';
}
You must call Model::create inside loop
public function store()
{
foreach ($this->createScheds as $sched) {
$createArray = array_merge([
'faculty_id' => $this->faculty_id,
'sem' => $this->sem,
'sy' => $this->sy,
],[
'corsdes' => $sched['corsdes'],
'c_time' => $sched['c_time'],
'day' => $sched['day'],
'room' => $sched['room'],
]);
Emp_sched::create($createArray);
}
return 'Schedules Saved!';
}

Adding data to Database in Laravel along with validated data and non validated data

I have a form in my view and on submit the fields are validated from the controller and I also need to add some data to database which doesn't need any validation. So how can I store these validated data and non validated(non validated data is set in controller it is not submitted along with the form in the view) data in short code.
This is my Controller
public function postRegister($type, Request $request){
$message = "Succesfully Registered, Login to access your Account";
$validatedData = $request->validate([
'name' => 'required|max:100',
'legal_type' => 'required|max:25',
'phonenumber' => 'required|max:12',
'email' => 'required|max:45',
'linkedinprofile' => 'required|max:250',
'address' => 'required:max:350',
'country' => 'required|max:15',
'email' => 'required|max:45',
'password' => 'required|max:120',
'terms' => 'required'
]);
LegalProfessional::create($validatedData);
// $lp = new LegalProfessional();
// $lp->lp_name = $request->input('name');
// $lp->lp_type = $request->input('legal_type');
// $lp->lp_phone = $request->input('phonenumber');
// $lp->lp_email = $request->input('email');
// $lp->lp_linkedin_profile = $request->input('linkedinprofile');
// $lp->lp_address = $request->input('address');
// $lp->country = $request->input('country');
// $lp->lp_membership_type = 'Premium';
// //$lp->lp_rfqs = $request->input('name');
// $lp->lp_username = $request->input('email');
// $lp->password = $request->input('password');
// $lp->save();
Session::flash('message', 'Successfully Registered!');
return redirect('/login');
In PHP you can add associative arrays together with the + operator. This will basicly add you extra fields to the associative array of $validatedData.
LegalProfessional::create(
$validatedData +
[
'lp_membership_type' => 'premium',
]
);
This is in my opinion the easiest and prettiest way to achieve what you want.
Edit
Remove terms, use PHP built in function unset(), that remove items if passed an arrray element.
unset($validatedData['terms']);
LegalProfessional::create(
...
To set a hashed password, just overwrite the $validatedData field.
$validatedData['password'] = Hash::make($request->input('password'));
LegalProfessional::create(
...

Cannot update data using vue.js in laravel

In my update form i have a file field that i want to update so i'm using following code and created a form object but when i pass form object i cannot get the data of form object in my controller.
let formData = new FormData();
formData.append('name', this.form.name);
formData.append('description', this.form.description);
formData.append('file_update', this.form.file_update);
axios.put(`/api/saveClass/${this.ItemId}`,formData,{headers:header})
.then((response)=>{
var msg = response.data.message;
if(response.status ==200){
this.$Progress.finish();
}else{
this.$Progress.fail();
}
this.$router.push(`/api/showClass`);
})
.catch(() => {
});
},
Laravel Controller:
public function update(Request $request,$id)
{
$ItemStore = class::find($id);
$this->validate($request,[
'name' => 'required|string|max:191|unique:class,name,'.$id,
'description' => 'required',
]);
}
I am getting name and description field is required but i'm passing data to it.

Using pluck() helper function in laravel

I'm building a small application on laravel 5.5 where I'm getting a list of multiple users with there information, from the forms as below format:
{
"name":"Test",
"description":"Test the description",
"users":[
{
"value":"XYZabc123",
"name":"Nitish Kumar",
"email":"nitishkumar#noeticitservices.com"
},
{
"value":"MFnjMdNz2DIzMJJS",
"name":"Rajesh Kumar Sinha",
"email":"rajesh#noeticitservices.com"
}
]
}
I just want to get the value key form the users array via laravel collection something like this:
$userIds = $request->users->pluck('value');
so that I can put them into query:
$user = User::all()->whereIn('unique_id', $userIds);
May be I'm doing most of the things wrong but my main motive is to use laravel collection or helper functions and make a cleaner code for this:
$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();
$users = $request->users;
$team = Team::create($teamData);
if($team)
{
$userIds = [];
foreach ($users as $user)
{
$getUser = User::where('unique_id', $user['value'])->get()->first();
$userIds [] = $getUser->id;
}
$team->users()->attach($userIds);
return response()->json(['message' => 'Created Successfully'], 200);
}
return response()->json(['message' => 'Something went wrong'], 500);
I'm still learning collections, any suggestions is appreciated. Thanks
Data that come from $request (form) isn't a collection. It's an array. If you need it to be collection, you should convert it to collection first.
PS. If you have multiple DB actions in single method, It's good to have DB transaction.
\DB::transaction(function () use ($request) {
// convert it to collection
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
});
// HTTP Created is 201 not 200
return response()->json(['message' => 'Created Successfully'], 201);
or you'll need something like this:
return \DB::transaction(function () use ($request) {
$users = collect($request->users);
$team = Team::create([
'name' => $request->name,
'description' => $request->description,
'unique_id' => str_random(),
]);
$team->users()->attach($users->pluck('value')->toArray());
return response()->json([
'message' => 'Created Successfully',
'data' => $team,
], 201);
});
I just want to get the value key form the users array via laravel collection
Just use map then:
$userIds = $request->users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});
Edit:
if $request->users is not a collection, make it one before calling map:
$users = collect($request->users);
$userIds = $users->map(function($user) {
return $user->value; // or $user['value'] ? not sure if this is an array
});

Resources