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

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(
...

Related

Validating form comaring two fields values

I'm trying to find Laravel 8 documentation on how to validate comparing two fields to each other. I'm creating an app that allows creating matches from teams in a database table, using the create() method in the controller. I looked into Laravel #Validation, even #Custom Validation Rules, but I can't find anything when comparing the two fields.
public function store(Request $request)
{
$validatedData = $request->validate([
'local_team' => 'required',
'local_score' => 'required|numeric',
'visitor_team' => 'required',
'visitor_score' => 'required|numeric',
]);
$score = new Score();
$score->local_team = $request->local_team;
$score->local_score = $request->local_score;
$score->visitor_team = $request->visitor_team;
$score->visitor_score = $request->visitor_score;
$score->save();
$new = true;
return redirect()->route('scores.show',
['id' => $score->id, 'new' => true]);
}
In my case, the 'local_team' and 'visitor_team' fields should be different. Any clue on how to do it?

add multiple langue using Astrotomic / laravel-translatable package and laravel

i am new in laravel and use Astrotomic / laravel-translatable package for translation
i have problem when i want to add two langue at same time.
i have name_en,name_ar,discription_an,disriptionar as inputs fields.
i get this error Creating default object from empty value
so how can I solve my problem
this is link of package https://github.com/Astrotomic/laravel-translatable
// start add data
public function store(CategoryRequest $request)
{
// prepare data
$validatedData = array(
'url' => $request->url,
'slug' => $request->slug,
'status' => $request->status,
'last_updated_by' => auth('admin')->user()->id,
'created_by' => auth('admin')->user()->id,
'created' => time(),
);
$translated = array(
'name_en' => $request->name_en,
'name_ar' => $request->name_ar,
'description_en' => $request->description_en,
'description_ar' => $request->description_ar,
);
//start define categoru is sub or main
$request ->sub ==1 ? $validatedData['parent_id'] = $request ->category_id: $validatedData['parent_id']=null;
// start update data
DB::beginTransaction();
$add = Category::create($validatedData);
$id = $add->id;
// strat update category report
$categoryReport = CategoryReport::create(
['status' =>$validatedData['status'],
'category_id' =>$id,
'created_by' =>$validatedData['created_by']
,'last_updated_by' =>$validatedData['last_updated_by']]);
$add->translate('ar')->name = $translated['name_ar'];
$add->translate('en')->name = $translated['name_en'];
$add->translate('ar')->description = $translated['description_ar'];
$add->translate('en')->description =$translated['description_en'];
$add ->save();
DB::commit();
return redirect()->back()->with('success','تم اضافه البيانات بنجاح');
}

How to write TDD code for user profile update in Laravel

I want to create a TDD first before using my function in the app.
I have already created the update function, update works but before that i want a test case running. So i have created this test case.
/** #test */
public function updateUser()
{
$this->withExceptionHandling();
//creating a user
$user = factory(User::class)->create();
//passing updating values
$response = $this->put('users/update_profile', [
'name' => 'name123',
'phoneno' => 9842345562,
'address' => 'newwwww'
]);
$this->assertEquals('name123', User::first()->name);
$this->assertEquals(9842345562, User::first()->phoneno);
$this->assertEquals('newwwww', User::first()->address);
}
//update function
public function update(UpdateProfileRequest $request)
{
$user = auth()->user();
$user->update([
'name' => $request->name,
'phoneno' => $request->phoneno,
'address' => $request->address
]);
session()->flash('success', 'User Proifile Updated');
return redirect(route('users.view-profile'));
}
Failed asserting that two strings are equal.
--- Expected
+++ Actual
## ##
-'name123'
+'Tad Predovic'
Only getting this error.
You should not rely on User::first() as your first record may not the one you just created. Instead refresh the model you already have to get the updated values from the DB after your new values are set. You can use $user-refresh() before your assertions
/** #test */
public function updateUser() {
$this->withExceptionHandling();
//creating a user
$user = factory(User::class)->create();
//signing in as the new user
$this->actingAs($user);
//passing updating values
$response = $this->put('users/update_profile', [
'name' => 'name123',
'phoneno' => 9842345562,
'address' => 'newwwww'
]);
//Get new values
$user->refresh();
$this->assertEquals('name123', $user->name);
$this->assertEquals(9842345562, $user->phoneno);
$this->assertEquals('newwwww', $user->address);
}

Method not allowed exception while updating a record

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpExceptionNomessage
I'm getting this error while trying to update a record in the database. Don't know what's the problem. This question might be a duplicate but I've checked all and couldn't find the answer. Please Help me with this.
Controller Update Method:
public function updateEvent(Request $request, $id=''){
$name = $request->name;
$startdate = date_create($request->start_date);
$start_date = $startdate;
$time = $request->start_time;
$start_time = $time;//date("G:i", strtotime($time));
$endDate = date_create($request->end_date);
$end_date =$endDate;
$time_e = $request->end_time;
$end_time = $time_e;//date("G:i", strtotime($time_e));
$location = $request->location;
$description = $request->description;
$calendar_type = $request->calendar_type;
$timezone = $request->timezone;
if ($request->has('isFullDay')) {
$isFullDay = 1;
}else{
$isFullDay = 0;
}
DB::table('events')->where('id', $id)->update(
array(
'name' => $name,
'start_date' => $start_date,
'end_date' => $end_date,
'start_time' => $start_time,
'end_time' => $end_time,
'isFullDay' =>$isFullDay,
'description' => $description,
'calendar_type' => $calendar_type,
'timezone' => $timezone,
'location' => $location,
));
// Event Created and saved to the database
//now we will fetch this events id and store its reminder(if set) to the event_reminder table.
if(!empty($id))
{
if (!empty($request->reminder_type && $request->reminder_number && $request->reminder_duration)) {
DB::table('event_reminders')->where('id', $id)->update([
'event_id' => $id,
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
}
else{
DB::table('event_reminders')->insert([
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
return redirect()->back();
}
Route:
Route::post('/event/update/{id}', 'EventTasksController#updateEvent');
Form attributes :
<form action="/event/update/{{$event->id}}" method="POST">
{{ method_field('PATCH')}}
i'm calling the same update function inside my calendar page and it working fine there. Don't know why it doesn't work here.
Check the routeing method.
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
patch should be the method called on route facade.
Change your route to patch:
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
For your comment:
You can send the method to the ajax call by something like data-method attribute on the element you click on,take the method and use it in your ajax call. see this question/answer for help. How to get the data-id attribute?

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

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);
}
}

Resources