I have this if statement, if no $address information has been added to a user, then create, else go on.
public function getIndexEditClient(Request $request, $id) {
$regions = DB::table("regions")->pluck("name","id");
$address = Address::where('id', $request->address_id)->with('region')->first();
if(empty($address)){
$address = Address::create([
'street_name',
'house_number',
'postcode',
'city_id',
'country_id',
'region_id'
]);
// assiociate address with user
//then save it
}else{
$data = $this->data->getEditClient($id);
$admins = $this->data->getAdmin();
return view('client.edit', [
'client' => $data,
'admins' => $admins,
'regions' => $regions,
'address' => $address
]);
}
}
The only thing is, i have to associate the user(client) with the addres # the commented lines. I don't get it to work.
try this:
$user->address()->associate($address);
$user->save();
Related
I'm creating a user registration form. I create a form in the Component. when the user registers he redirects to the user page where he sees all users. when he wanted to edit or update something from in his details he redirects to the same registration form page but this will be a new URL and new Title. I'm getting an undefined variable $title and $url error. when I pass data from the controller to view I get this error.
Registration Form Controller
public function create(Request $request)
{
$url = url('/register');
$title = ("Registration Form");
$data = compact( 'url');
return view('RegistrationForm')->with($data);
}
public function store (Request $request)
{
$request->validate(
[
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'password' => 'required',
'confirm_password' => 'required|same:password|min:8',
'address' => 'required',
'country' => 'required',
'state' => 'required',
'city' => 'required',
'gender' => 'required',
'tearms_and_conditions' => 'required',
],
[
'firstname.required' => 'Please enter your First Name',
'lastname.required' => 'Please nter your Last Name',
'email.required' => 'Please enter an Email',
'password.required' => 'Please Enter a Password'
],
);
$users = new Users;
$users->firstname = $request['firstname'];
$users->lastname = $request['lastname'];
$users->email = $request['email'];
$users->password = md5($request['password']);
$users->address = $request['address'];
$users->country = $request['country'];
$users->state = $request['state'];
$users->city = $request['city'];
$users->gender = $request['gender'];
$users->date_of_birth = $request['date_of_birth'];
$users->save();
return redirect('/register/view');
}
public function view (Request $request)
{
$users = Users::all();
$data = compact('users');
return view('user-view')->with($data);
}
public function delete($id)
{
$user = Users::find($id);
echo "<pre>";
print_r ($user);
die;
return redirect('/register/view');
}
public function edit($id)
{
$user = Users::find($id);
if (is_null($user))
{
return redirect('/register/view');
}
else
{
$url = url("user/update"."/". $id);
$title = "Update Details";
$data = compact('user', 'url', 'title');
return redirect('/register')->with($data);
}
}
public function update($id, Request $request)
{
$user = Users::find($id);
$users->firstname = $request['firstname'];
$users->lastname = $request['lastname'];
$users->email = $request['email'];
$users->address = $request['address'];
$users->country = $request['country'];
$users->state = $request['state'];
$users->city = $request['city'];
$users->gender = $request['gender'];
$users->date_of_birth = $request['date_of_birth'];
$users->save();
return redirect('register/view');
}
}
Route
Route::get('/register', [RegistrationFormController::class, 'index']);
View
<body>
<h1> {{$title}} </h1>
<x-registration-form-component :country="$country" :url="$url" />
RegisreationFormComponent
You have to pass the $data variable as the second argument of the view() method:
public function index ()
{
$url = url('/register');
$title = "Registration Form";
$data = compact('title', 'url');
return view('RegistrationForm', $data);
}
First, to answer your question:
When you use the compact method, you are placing those values in an array. You would need to call them like so:
{{ $data['title'] }}
{{ $data['url'] }}
However, you could clean the code up a little bit like this:
public function index()
{
return view('RegistrationForm', [
'url' => url('/register'),
'title' => 'Registration Form',
]);
}
You can then use them in the blade file like so:
{{ $url }}
{{ $title }}
I'm using Laravel 5.3's validation as follows:
In my model:
public static $validation = [
'name' => 'required',
'username' => 'required|alpha|unique:companies',
'email' => 'required|email|unique:companies',
];
In my controller, I post to the same CompanyController#dataPost method when creating a new item or when editing one:
public function dataPost(Request $request) {
// First validation
$this->validate($request, Company::$validation);
$id = $request->id;
if ($id > 0) {
// Is an edit!
$company = Company::find($id);
$company->update($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.editedsuccessfully'));
} else {
// Is a create
$company = new Company($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.createdsuccessfully'));
}
return redirect()->route('companyindex');
}
The unique validation works ok when I create a new item, but causes an error (as in it flags the username as already existing) when editing an item.
Any idea how to avoid this? Even in an edit I'd still want to ensure the data is unique if it's changed, but if the value is the same as before then ignore the validation.
I know I could do this manually, but I wonder if there is a built-in way to avoid this.
Thanks!
I think you can try this:
public static $validation = [
'name' => 'required',
'email' => Auth::check()
? 'required|email|unique:companies,email,'.Auth::id()
: 'required|email|unique:companies,email',
'username' => Auth::check()
? 'required|alpha|unique:companies,username,'.Auth::id()
: 'required|alpha|unique:companies,username',
];
Hope this work for you !!!
You can update email field with unique property as well.
Following rule will check uniqueness among all emails in other column except current one.
Try this one,
'email' => 'required|unique:users,email,' . $userId
here $userId refers to id of user currently updated.
You can see official docs here
You can create different validation methods for insert or update
public static $validation_update = [
'name' => 'required',
'username' => 'required|alpha',
'email' => 'required|email',
];
public static $validation_add = [
'name' => 'required',
'username' => 'required|alpha|unique:companies',
'email' => 'required|email|unique:companies',
];
Then apply validation in condition
public function dataPost(Request $request) {
// First validation
$id = $request->id;
if ($id > 0) {
// Is an edit!
$this->validate($request, Company::$validation_update);
$company = Company::find($id);
$company->update($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.editedsuccessfully'));
} else {
// Is a create
$this->validate($request, Company::$validation_add);
$company = new Company($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.createdsuccessfully'));
}
return redirect()->route('companyindex');
}
$id = $request->id;
if ($id > 0) {
// Is an edit!
$this->validate($request, Company::$validation_update);
$company = Company::find($id);
$company->update($request->all());
$company->save();
My application gives employees of a company the ability to edit their data(example: address). Once they change any of it, a manager gets an e-mail with their new information. The problem is that an email is sent every time a employee clicks update. I need the application to compare the info in the database and only send an email if there's new information. What is good way to achieve this? I am sorry I forgot to mention, the email needs to contain only the new iformation. So isDirty() would not work for me.
public function editcredentials_action(Request $request)
{
$user = Auth::user();
$address = $user->address;
$this->validate($request, [
'password' => 'max:255',
'language' => 'integer',
'facebook_profile' => 'max:255',
'twitter_profile' => 'max:255',
'street' => 'max:255',
'house_number' => 'max:255',
'city' => 'max:255',
'zip_code' => 'max:255',
'country' => 'max:255',
]);
if (!empty($request->get('password')) && $request->get('password')) {
$user->password = bcrypt($request->get('password'));
}
$user->facebook_profile = $request->get('facebook_profile');
$user->twitter_profile = $request->get('twitter_profile');
$user->language_id = $request->get('language');
$user->save();
if (!$address) {
$address = new UserAddress();
$address->user_id = $user->id;
}
$address->street = $request->street;
$address->house_number = $request->house_number;
$address->city = $request->city;
$address->zip_code = $request->zip_code;
$address->country = $request->country;
$address->save();
$data = [
'email' => $user->email,
'facebook' => $user->facebook_profile,
'twitter' => $user->twitter_profile,
'name' => $user->name . ' ' . $user->lastname,
'address' => $address,
];
Mail::send('emails.user-update', $data, function ($message) use ($data) {
$message->from('no-reply#example.com', 'Profile change');
$message->to('profilechange#example.com');
$message->subject('Profile change: ' . $data['name']);
});
Session::flash('message', trans('app.global.saved'));
return back();
//return redirect()->route('profile.edit-credentials');
}
I don't think isDirty() will work here, but you can save user data in the beginning:
$params = ['language', 'facebook_profile', 'twitter_profile', 'name'];
$oldUserData = auth()->user()->only($paramsToCOmpare);
Then compare the data after using save() method:
if (count(array_diff($oldUserData, $user->only($paramsToCompare))) > 0) {
// Data was changed.
}
You can do the same for UserAddress model. For password just check if it was filled in the form (since you're not displaying it anyway):
if (!empty($request->password))
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().
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