update multiple columns value at once in laravel - php

I am trying to update attendance column outtime of all selected employees with checkout time.During intime check-in time successfully stored in the database, but I am getting trouble with the update. I did something like below, but it's updating the only first row. What should be written query would someone help me, please?
AttendanceController.php
public function checkout(Request $request)
{
$request->validate([
'outtime' => 'required',
'employee_id' => 'required',
]);
$outTime = Carbon::parse($request->outtime)->format('H:i:s');
$date = date('Y-m-d');
$employeeIds = $request->employee_id;
$data = [];
foreach ($employeeIds as $employeeId) {
$data[] = [
'employee_id' => $employeeId,
'attendance_date' => $date,
];
}
$update = Attendance::where('employee_id', $data)
->where('attendance_date', $date)
->update([
'outtime' => $outTime
]);
return back()->with('success', 'Checked Out');
}

Use this:
whereIn('employee_id', $employeeIds)

Related

Why would the update produce this result ` {"email":"try#gmail.com"}` in the database

when i try to update email column for the user i get a weird input in the database and i don't see why. The output in the email column in the database looks something like this {"email":"try#gmail.com"} instead of just the email
HomeController
protected function createMail(Request $request)
{
$data = request()->validate([
'email' => 'required',
]);
$id = Auth::guard('web')->id();
User::where('id', $id)->update(['email' => $data]);
}
$data in your case is defined as a result of ->validate() function, but you need the value of email.
Value can be accessed with $request->get('email').
so your function should look like this:
protected function createMail(Request $request)
{
$this->validate($request, [
'email' => 'required',
]);
$id = Auth::guard('web')->id();
User::where('id', $id)->update(['email' => $request->get('email')]);
}
you are updating wrong value and it should be like this
protected function createMail(Request $request)
{
$this->validate($request, [
'email' => 'required',
]);
$id = Auth::guard('web')->id();
User::where('id', $id)->update(['email' => $request->get('email')]);
}
as you see request->get('email') instead of ['email' => $data]

Exclude a validated array object from inserting into db

I'm trying to exclude an object from an array from inserting into a database only after validation. The code sample is below
public function store(Request $request)
{
//
$request->merge([
'added_by' => auth('api')->user()->id,
]);
$travel = TravelSummary::create( $this->validateRequest($id = null) );
event(new TravelRequestCreatedEvent($travel, $action = 'added travel request'));
return (new TravelSummaryResource($travel))
->response()
->setStatusCode(Response::HTTP_CREATED);
}
Below is the array of validated fields
private function validateRequest($id){
return request()->validate([
'travel_request_no' => $id ? 'required' : 'required|unique:travel_summaries',
'purpose' => 'required',
'total' => 'nullable',
'cash_advance' => 'nullable',
'advance_amount' => 'nullable|lte:total',
'added_by' => 'required'
]);
}
Can the total be excluded only after validation?
use
$data = $request->only(['travel_request_no', 'purpose', 'cash_advance', 'advance_amount', 'advance_amount']);
or
$data = $request->except(['total']);
after validation then pass that data to create model. here is an example.
$this->validateRequest($id = null);
$data = $request->only(['travel_request_no', 'purpose', 'cash_advance', 'advance_amount', 'advance_amount']);
//or you can use except
//$data = $request->except(['total']);
$travel = TravelSummary::create($data);
You can unset the data you wish to exclude, after validation, like so:
// The validator will return the validated data as an array
$data = $this->validateRequest($id = null);
// This will remove the key and value from the array.
unset($data['total']);
$travel = TravelSummary::create($data);

Array to string conversion (laravel 7)

I want to make a quiz app in Laravel and I've got some error: array to string conversion
This is my controller:
public function validateForm1($request)
{
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'options.*' => 'required|string',
'correct_answer' => 'required',
]);
}
public function buat(Request $request)
{
$data = $this->validateForm1($request);
$question = (new Pertanyaan)->storeQuestion($data);
$Answer = (new Jawaban)->storeAnswer($data,$question);
return redirect()->back()->with('message','Pertanyaan berhasil disimpan');
}
This is my question model:
public function storeQuestion($data)
{
return Pertanyaan::create($data);
}
This is my answer model:
public function storeAnswer($data, $question)
{
foreach ($data['options'] as $key => $option) {
$is_correct = false;
if ($key == $data['correct_answer']) {
$is_correct = true;
}
$answer = Jawaban::create([
'question_id' => $question->id,
'answer' => $option,
'is_correct' => $is_correct,
]);
}
}
You have to use like this
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'correct_answer' => 'required',
]);
Then your error remove automatically array to string conversion
this error i got when i use guarded in model, so i change it to fillable and it work properly.
sorry if im not capturing all of my model.
after read the documentation about special variable eloquent, i lil understand.
here the link i read but in indonesian leanguage. and sorry for my bad english sir. im new here
https://id-laravel.com/post/mengenal-eloquent-variable-spesial/
When I had this error, it was caused by an error in my Model. I had the table name formatted as an array, like protected $table = ['log'];. Correcting this to protected $table = 'log'; fixed the problem.

Laravel: Check if record exists Before Insertion

I have two tables: assignments table(columns assignment_id, Staff Name, asset_id, department, date, status), and an assets table (columns asset_id, tag_name, serial_number, model_number, color). The asset table columns are linked with the assignments table. I want to perform an insertion into the assignments table but before the insertion, i want to check if the asset_id already exists in the assignments table & if it's status = 'Active' then the insertion should throw an error/shouldn't happen.
AssignmentsController
class AssignmentController extends Controller
{
public function assignment(){
$assignments = Assignment::all();
return view('assignment/index', ['assignments' => $assignments]);
}
public function add(Request $request){
$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignments = new Assignment;
$assignments ->assignment_id = $request->input('assignment_id');
$assignments ->staff_id = $request->input('staff_id');
$assignments ->asset_id = $request->input('asset_id');
$assignments ->department_id = $request->input('department_id');
$assignments ->date = $request->input('date');
$assignments ->status = $request->input('status');
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}
$assignments ->save();
return redirect('/assignment/index') ->with('info', 'New Assignment Saved Successfully!');
}
Assginment.php
class Assignment extends Model
{
protected $primaryKey = 'assignment_id';
public function asset()
{
return $this->belongsTo('App\Asset', 'asset_id');
}
}
The below variable and if statement in the AssignmentsController always throws the error in the if statement whether it's true or not and the insertion doesn't happen but when the whole statement is cleared, the insertion happens.
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}
So i want a way to check if the the record to be inserted already exists with conditions as if asset_id exists then check for it's status if it's ='Active' then throw an error but if not then insertion happens. Please help if you understand it. Thanks in advance.
You can just do:
public function add(Request $request){
$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignment = Assignment::firstOrNew([
"status" => "Active",
"asset_id" => $assignments->asset_id
], $request->all());
abort_if($assignment->exists(), 405, 'Trying to assign an already assigned asset');
$assignment->save();
return redirect('/assignment/index')
->with('info', 'New Assignment Saved Successfully!');
}
The Solution
$count = Assignment::where('asset_id', '=' ,$assignments->asset_id)->
where('status', '=' ,'Active')->
count();
if($count == 1 && $assignments->status != 'Disable') {
abort(405, 'Trying to assign an already assigned asset');
}
The mistake in my code: I was counting all Assignments and if there is any active status i got an error....I needed to check exactly that assignment which i want to assign which was either active or disable then the assignment should occur or not pertaining it's status(active/disable). Thanks Y'all esp apokryfos.

can we add properties on request in laravel

I want to use single validate for birthday year, birth month, birth day as birthday for registration in laravel 5.4 here is my code
public function register(Request $request)
{
// here i want to add bithday input on reqeust but nothing happen
$request->birthday = implode('-', array(
$request->birth_year,
$request->birth_month,
$request->birth_date
));
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
return redirect()->back()->with('info', 'User successfully registered');
}
nothing happen with that code, I can validate those 1 by 1 using date_format. the problem is what if the user select February and day is 31
According to the source, you can use the merge method.
$request->merge(['birthday' => implode('-', [
$request->birth_year,
$request->birth_month,
$request->birth_date
])]);
There are many ways to do that. For example, you can use add() method to add data to the Request object:
$request->request->add(['birthday', implode('-', [
$request->birth_year,
$request->birth_month,
$request->birth_date
)]);
But here, I'd just do something like this:
$data = $request->all();
$data['birthday'] = implode('-', [
$request->birth_year,
$request->birth_month,
$request->birth_date
]);
$this->validator($data)->validate();
event(new Registered($user = $this->create($data)));
my way is:
$all = $request->all();
$year = $all['birth_year'];
$month = $all['birth_month'];
$day = $all['birth_date'];
// Create Carbon date
$date = Carbon::createFromFormat('Y-m-d', $year.'-'.$month.'-'.$day);
// $date = Carbon::createFromFormat('Y-m-d', $request->birth_year.'-'.$request->birth_month.'-'.$request->birth_date); another way
//add new [birthday] input
$request->request->add(['birthday' => $date->format('Y-m-d')]);
$validatedData = $request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string',
'birthday' => 'required|date_format:Y-m-d|before:today',// validate birth day
]);
Hope this helps someone

Categories