can we add properties on request in laravel - php

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

Related

Problem with updating date from form to database

I am trying to update date_of birth column in database and when I submit my form I get this error
DateTime::__construct(): Failed to parse time string (25/03/1995) at position 0 (2): Unexpected character
Now in my blade I formated date of birth to show d/m/Y and when updating I think it updates Y/m/d, because when I remove format function from my blade it works fine. So I need help on how to update with format('d/m/Y') in my database and how to validate it properly in my form request validation. Any help is appreciated. Here is my code.
index.blade.php
<input type="text" placeholder="dd/mm/yyyy" name="date_of_birth" value="{{ $userForShowProfile->date_of_birth ? $userForShowProfile->date_of_birth->format('d/m/Y') : "" }}">
UserController.php
public function updateProfileCharacteristics(UpdateProfileCharacteristicsRequest $request)
{
$user = Auth::user();
$user->update(
[
'date_of_birth' => $request->date_of_birth,
'age' => Carbon::now()->diffInYears($request->date_of_birth),
'updated_at' => Carbon::now()
]
);
return redirect()->route('profile.show', [$user->username]);
}
UpdateProfileCharacteristicsRequest.php
public function rules()
{
return [
'date_of_birth' => ['date'],
];
}
Since you are sending the date in a custom format in the request, you will need to parse it to a format that matches the one in the database column before inserting it:
$user->update(
[
'date_of_birth' => Carbon::createFromFormat("d/m/Y", $request->date_of_birth)->format('Y-m-d'), // parse the right format here
'age' => Carbon::now()->diffInYears(Carbon::createFromFormat("d/m/Y", $request->date_of_birth)),
'updated_at' => Carbon::now()
]
);
And for that date format to pass validation you can use the date_format:format rule instead of date:
public function rules()
{
return [
'date_of_birth' => ['date_format:"d/m/Y"'],
];
}
What is the column type in you database migration? If it is check if it DATE or DATETIME or TIMESTAMP, It is supposed to be DATE hence you can format your date to be Y-m-d.
If you are to save a DATE to DB it should be in the format of Y-m-d.
so try this:
public function updateProfileCharacteristics(Request $request)
{
$user = Auth::user();
$user->update([
'date_of_birth' => Date('Y-m-d',strtotime($request->date_of_birth)),
'age' => Carbon::now()->diffInYears($request->date_of_birth),
'updated_at' => Carbon::now()
]);
return redirect()->route('profile.show', [$user->username]);
}

update multiple columns value at once in laravel

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)

How to customize redirect url after request validation fails in laravel 5?

I am using use Illuminate\Http\Request to access form request. For example if my form request is coming from http://localhost:8012/test_project/public after validating it is automatically redirecting to http://localhost:8012/test_project/public with error messages but i want it to redirect to http://localhost:8012/test_project/public#myform because my form is visible in #myform section. So how can we do it. I am using Laravel 5.0
Following is my method code in controller that handles my request
public function add_user(Request $request){
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'mobile' => 'required|regex:/^[789]\d{9}+$/|unique:users,mobile',
'pass' => 'required|min:6',
'cpass' => 'required|same:pass'
]);
$user = new Myuser;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->mobile = $request->input('mobile');
$user->pass = md5("EEE".$request->input('pass'));
$user->register_on = date('Y-m-d');
$user->user_type = 'Free';
$user->last_login = date('Y-m-d H:i:s');
$user->status = 'Active';
$user->save();
$insertedId = $user->sno;
$uid = "UID".$insertedId;
Myuser::where('sno', $insertedId)
->update(['uid' => $uid]);
//echo $insertedId;
return redirect('')->with('message', 'Registered Successfully');
}
If you make your own Validator instead of using $this->validate(), you can have more control over what happens on a failed validation. Here is an example from the laravel documentation. Make sure you add use Validator; to the top of your php file. https://laravel.com/docs/5.3/validation
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}

Retry logic on model save - Laravel

User_code is generated and must be unique. What would be the easiest/cleanest way to do retry logic on this model save? I would like to verify the generated code first, and then if it's not found on the users table, create the user, if found, loop to retry. What would be the syntax for that? Thanks
public function create(array $data)
{
$user = User::create([
'user_name' => 'My user name',
'user_code' => bin2hex(openssl_random_pseudo_bytes(16))
]);
$user->save();
return $user;
}
Why don't you check the database when generating the code? That way, you only try to create once you got it right and the end user doesn't have to face an error that is not up to him/her.
do {
$code = bin2hex(openssl_random_pseudo_bytes(16));
$record = User::where('user_code', $code)->get();
} while(!empty($record));
$user = User::create([
'user_name' => 'My user name',
'user_code' => $code
]);
return $user;
You could avoid the retry:
public function create(Request $request)
{
$request->merge(['user_code' => bin2hex(openssl_random_pseudo_bytes(16))]);
$this->validate($request, [
'user_name' => 'required|unique:users',
'user_code' => 'required|unique:users',
]);
$user = new User;
$user->user_name = $request->user_name;
$user->user_code = $request->user_code;
$user->save();
return $user;
}
You should create a unique string from the beginning. Still go for validation, of course.
public function create(Request $request)
{
$user_code = bcrypt($request->user_name . openssl_random_pseudo_bytes(16));
$request->merge(['user_code' => $user_code]);
$this->validate($request, [
'user_name' => 'required|unique:users',
'user_code' => 'required|unique:users',
]);
$user = User::create($request);
return $user;
}
A save() is implied by create().

Is it possible to access two models from a single function of a controller in Laravel4?

So I'm trying to insert values into two tables from a single form using Laravel4.
this is my Store() function.Am i doing it right..?
I know i should be using two controllers AddressController.php and PeopleController.php.., but can i use a single controller to insert into two tables using a single form.?
public function store()
{
$rules = array(
'address_id' => 'required',
'contact_id' => 'required',
'prefix' => 'required',
'firstname' => 'required',
'middlename' => 'required',
'lastname' => 'required',
'suffix' => 'required',
'occupation' => 'required',
'gender' => 'required',
'comment' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
$user= Auth::user();
if (!empty($user->id))
$user_id=$user->id;
// process the login
/*if ($validator->fails()) {
return Redirect::to('people/create')
->withErrors($validator);
} else {*/
// store
$person = new Person;
$person->user_id=$user_id;
$person->address_id =Input::get('address_id');
//$person->contact_id = Input::get('contact_id');
$person->prefix = Input::get('prefix');
$person->firstname =Input::get('firstname');
$person->middlename =Input::get('middlename');
$person->lastname =Input::get('lastname');
$person->suffix =Input::get('suffix');
$person->occupation =Input::get('occupation');
$person->gender =Input::get('gender');
$person->comment =Input::get('comment');
//$person->user_id =Input::get('user_id');
$person->save();
$validator = Validator::make($data = Input::all(), Address::$rules);
$address->address1 = Input::get('address1');
$address->address2 = Input::get('address2');
$address->apt = Input::get('apt');
$address->city = Input::get('city');
$address->state = Input::get('state');
$address->zip = Input::get('zip');
$address->country = Input::get('country');
$address->save();
// redirect
Session::flash('message', 'Successfully created new Employee!');
//return Redirect::to('addresses/create');
return Response::json($person);
}
As long as you've defined a relationship between the person and address models, then you can use the person model's push() method which is designed to save multiple related models in a single step
Note that if you had fillable defined for your models, you could also eliminate a lot of those boilerplate $person->prefix = Input::get('prefix'); statements from your code as well

Categories