Three short questions:
How to set swiftmailer sending carbon copy or/and a blind carbon copy of mail?
Where could I get information about this? I have read articles about Swiftmailer but didn't find anything about bc and bcc
Is my intention supported by swiftmailer, at all?
You need to use ->setBcc($email) and ->setCc($email) repectively.
Refer to the MessageInterface class to see the available methods,
See a method below from my ContactForm Model which sends an email with bcc cc and to
/**
* #param $email
*/
private function sendEmail($email)
{
return Yii::$app->mailer->compose()
->setTo($email)
->setBcc($email)
->setCc($email)
->setFrom([$email => 'Omer Aslam'])
->setSubject('some subject')
->setTextBody('test text body email')
->send();
}
Yes it is possible
Hope it helps
Related
I need to translate Laravel's default validation errors in JSON files. The problem is if I want to overwrite a translation, like the 'required' validation error in resourses/lang/de.json file, it doesn't work.
The reason why I have to do this is the Phrase translator system what I am using.
Any idea? Thanks!
UPDATE
After some research, now I see what is my 'problem'. Laravel using the trans() function for translating the validation errors but if you want to use Laravel's JSON translation then you have to use the __() function. Okey, I know why they are doing in that way, because the validation errors are structured by 'short keys' and the JSON formatted translation if for use strings as keys.
But what if I still want to translate the default errors in the JSONish (I know it's a futuristic word) way? Follow my solution here:
First of all you have to create a form request (https://laravel.com/docs/7.x/validation#creating-form-requests):
php artisan make:request UserUpdateRequest
In the newly created form request file you have to overwrite the messages function to be able to translate the validation errors:
namespace App\Http\Requests\v1;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Exceptions\ApiValidationException;
class UserUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => ['required', 'string', 'min:3', 'max:255'],
];
}
/**
* Get custom messages for validator errors.
*
* #return array
*/
public function messages()
{
return [
'name.required' => __('The user name is required.'),
'name.string' => __('The user name must be a string.'),
'name.min' => __('The user name must be at least three characters.'),
'name.max' => __('The user name may not be greater than 255 characters.'),
];
}
}
Now we have to create the translations files (https://laravel.com/docs/7.x/localization#using-translation-strings-as-keys) and put the new translation strings into them.
# resourses/lang/de.json
{
"The user name is required." : "The user name is required.",
"The user name must be a string." : "The user name must be a string.",
"The user name must be at least three characters." : "The user name must be at least three characters.",
"The user name may not be greater than 255 characters." : "The user name may not be greater than 255 characters."
}
And that's all.
I hope this description of translation process it will be useful for someone else.
I need to translate Laravel's default validation errors in JSON files. The problem is if I want to overwrite a translation, like the 'required' validation error in resourses/lang/de.json file, it doesn't work.
The reason why I have to do this is the Phrase translator system what I am using.
Any idea? Thanks!
ANSWER
After some research, now I see what is my 'problem'. Laravel using the trans() function for translating the validation errors but if you want to use Laravel's JSON translation then you have to use the __() function. Okey, I know why they are doing in that way, because the validation errors are structured by 'short keys' and the JSON formatted translation if for use strings as keys.
But what if I still want to translate the default errors in the JSONish (I know it's a futuristic word) way? Follow my solution here:
First of all you have to create a form request (https://laravel.com/docs/7.x/validation#creating-form-requests):
php artisan make:request UserUpdateRequest
In the newly created form request file you have to overwrite the messages function to be able to translate the validation errors:
namespace App\Http\Requests\v1;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Exceptions\ApiValidationException;
class UserUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => ['required', 'string', 'min:3', 'max:255'],
];
}
/**
* Get custom messages for validator errors.
*
* #return array
*/
public function messages()
{
return [
'name.required' => __('The user name is required.'),
'name.string' => __('The user name must be a string.'),
'name.min' => __('The user name must be at least three characters.'),
'name.max' => __('The user name may not be greater than 255 characters.'),
];
}
}
Now we have to create the translations files (https://laravel.com/docs/7.x/localization#using-translation-strings-as-keys) and put the new translation strings into them.
# resourses/lang/de.json
{
"The user name is required." : "The user name is required.",
"The user name must be a string." : "The user name must be a string.",
"The user name must be at least three characters." : "The user name must be at least three characters.",
"The user name may not be greater than 255 characters." : "The user name may not be greater than 255 characters."
}
And that's all.
I hope this description of translation process it will be useful for someone else.
Based on the answer provided I digged some more and discovered the double underscore function is working as intended in the default validation.php file! I tested it with Laravel 5.6.
I have a similar issue that I need to provide a way for users to give translations for everything in the web app and so I started to test the solution. While it works as explained it does not use the placeholder attribute anymore and therefore it is not very scalable in my situation.
I tested using the double underscore function with the following requirements:
locale and fallback_locale are set to 'en' in app.php
There is an en folder inside resources/lang
There is a validation.php file inside the en folder
There is a locale json file (like pt-br.json) inside resources/lang folder
The application sets the locale dynamically using App::setlocale()
All that is needed to change in validation.php is to use the function in the string, like the following:
# before
'unique' => 'The :attribute has already been taken.',
#after
'unique' => __('The :attribute has already been taken.'),
And the json file needs to have a string key with the same string, like the following:
"The :attribute has already been taken.": ":attribute j\u00e1 existe!"
Thanks for making me thinking more on this problem. I think Laravel should have better support for use cases like this.
I installed dektrium\user and dektrium\rbac\ modules for manage user and access control.Related tables and files installed completely and i can see several tabs in /user/admin path ( Users, Roles, Permissions, Rules, Create ) for work with modules.I can manage users perfectly(create user, reset password, edit,..). buy I can not create a rule.
I created a class in app\rbac\rules folder named AuthorRule :
<?php
namespace app\rbac\rules;
use yii\rbac\Rule;
use app\models\News;
/**
* Checks if authorID matches user passed via params
*/
class AuthorRule extends Rule
{
public $name = 'isAuthor';
/**
* #param string|int $user the user ID.
* #param Item $item the role or permission that this rule is associated with
* #param array $params parameters passed to ManagerInterface::checkAccess().
* #return bool a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{
return isset($params['news']) ? $params['news']->createdBy == $user : false;
}
}
(I created news class with model,controler,views)
but when I entered name and class rule in my modules. Neither the data is logged nor the error message. I can't add the rest of the sections until I get into the rule.
I certainly hope the OP has solved their problem by now, but other people might encounter it.
First a remark: as described, the Save fails silently. This is because the form is submitted with Ajax (XHR). The error can be seen in the browser console.
This is the relevant part of the error message:
preg_match(): Compilation failed: invalid range in character class at offset 8
Due to the architecture of Yii 2, the actual regexp is a little tricky to find. It is in the model for Rules in yii2-rbac vendor/dektrium/yii2-rbac/models/Rule.php, line 86.
The original regexp is /^[\w][\w-.:]+[\w]$/
PHP 7.3 uses the PCRE2 library instead of the original PCRE, and the pattern above is wrong. The dash (-) needs to be escaped.
The full line should now be:
['name', 'match', 'pattern' => '/^[\w][\w\-.:]+[\w]$/'],
As the yii2-rbac package is abandoned, you can just modify the file. A more robust solution would be to override the Class.
Hi I followed a tutorial to implement a friend system. It all works find, but I need to post other columns to the row that just the id's. How would I expand that.
This is the method that is accessed when the add friend button is clicked
public function getAdd($id){
$user = User::where('id', $id)->first();
//After passing all checks. Add other account
Auth::user()->addFriend($user);
echo "Sent";
}
AddTenancy Method
public function addFriend(User $user){
$this->friendsOf()->attach($user->id);
}
I assume the relationship is many-to-many between users. And you need to add additional data to the pivot.
Here's how you'd do that:
public function addFriend(User $user){
$this->friendsOf()->attach($user->id, ['another_col' => 'some data']);
}
Replace 'another_col' and some data with your column and your data. You can also add more than 1 column into the array.
I have a simple unsubscribe function in my Unsubscribed controller.
if ($this->Unsubscribe->save($this->data['Unsubscribes'])) {
// success
$this->Session->setFlash('Your email has been unsubscribed!');
$this->redirect('/unsubscribes/unsubscribe');
} else {
// error
$this->Session->setFlash('There was an error!');
$this->redirect('/unsubscribes/unsubscribe');
}
Here is the problem. I want to set the email address in the database as unique. So if someone enters the email address multiple times (or we already have it in our unsubscribe list), we are not populating the database with duplicate records. However, I want the visitor to know they have been added to the database (so they know they are unsubscribed).
Is there a way to detect the Duplicate entry error from the controller so I can equate that to a success? The caveat, I don't want to create a extended app_model. Any ideas? Can it be done? How is the best way to do this?
SOLUTION: Here is the final solution I implemented. I added the validation (as suggested by the chosen answer below) and I updated my controller as follows:
// error
if(isset($this->Unsubscribe->validationErrors['email'])){
$error = 'Your email has been unsubscribed!';
} else {
$error = 'Something went wrong. Please try again.';
}
$this->Session->setFlash($error);
$this->redirect('/unsubscribes/unsubscribe');
What about using the isUnique validation rule? Then just use the validation error to inform the user.
var $validate = array(
'login' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken.'
)
);
Stole this directly from the cookbook. Section 4.1.4.14 isUnique to be precise.
I think you can do it like this:
if ($this->Unsubscribe->find('count',array('conditions'=>array('email'=>$this->data['Unsubscribes']['email']))) > 0 )
{
$this->Session->setFlash('duplicate email!');
$this->redirect('/unsubscribes/unsubscribe');
}
//then do your stuff
It depends. Is there any other error that might occur that you want to display? Or is this the only error that may occur? In case of the latter, just don't check:
$this->Unsubscribe->save($this->data['Unsubscribes']);
// I don't care if that actually saved or not,
// unless something horrible happened the email is in the database
$this->Session->setFlash('Your email has been unsubscribed!');
$this->redirect('/unsubscribes/unsubscribe');
Otherwise, you can use the invalidFields() method to find out what went wrong.
I want to find the longitude and latitude of place with a the help to a zipcode.
Can anyone tell me how to do that?
An example in actionscript what be very much helpful for me. Because i am making a project in Flex.
Regards
Zee
Do you have access to a long/lat database? if not, i believe you can use the google maps API to do that lookup.
Oh .. I just noticed Chris' answer. I am not familiar with geonames. You might also want to get familiar with "http://freegeographytools.com/" which has a ton of geocoding, gps, etc. resources for a whole range of projects.
Ahhh ... I just visited Eric's blog post. That is excellent! I will definitely hook up with google for more details in a future project.
If you are looking for on demand geocoding, use Google. They provide a simple pox web service version.
I wrote a blog about this a while back. Check out this link for step by step instructions for using this simple geocoding.
Cheers,
Eric
I got my solve you can also
function getLatLong($code) {
$mapsApiKey = 'ABQIAAAAsV7S85DtCo0H9T4zv19FoRTdT40ApbWAnDYRE0-JyP5I6Ha9-xT9G5hCQO5UtOKSH5M3qhp5OXiWaA';
$query = "http://maps.google.co.uk/maps/geo?q=".urlencode($code)."&output=json&key=".$mapsApiKey;
$data = file_get_contents($query);
// if data returned
if($data) {
// convert into readable format
$data = json_decode($data);
$long = $data->Placemark[0]->Point->coordinates[0];
$lat = $data->Placemark[0]->Point->coordinates[1];
return array('Latitude'=>$lat, 'Longitude'=>$long);
} else {
return false;
}
}
There are several places to get zip code databases, in several formats. Load it into your favorite RDBMS, and query away.
Alternatively, you can use someone else's web service to look up the value for you. Other answers have posted possible web services; also, geocoder.us appears to have support for ZIP code lookup now as well.
There is now a better solution for this using the most recent Google Maps API (v3). The following is a slightly modified example from multiple sources. I have to give most of the credit to them. It's PHP, using cURL to retrieve the data from Google, but you could also use Ajax.
function address_lookup($string){
$string = str_replace (" ", "+", urlencode($string));
$details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$string."&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
// If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
if ($response['status'] != 'OK') {
return null;
}
$geometry = $response['results'][0]['geometry']['location'];
$array = array(
'lat' => $geometry['lat'],
'lng' => $geometry['lng'],
'state' => $response['results'][0]['address_components'][3]['short_name'],
'address' => $response['results'][0]['formatted_address']
);
return $array;
}
$zip= '01742';
$array = address_lookup($zip);
print_r($array);
The easiest way out is using GoogleMap Api. Say you have a zipcode in a varible $zipcode.
$latlongUrl = 'http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:'.$zipcode;
$data = file_get_contents($latlongUrl); // you will get string data
$data = (json_decode($data)); // convert it into object with json_decode
$location = ($data->results[0]->geometry->location); // get location object
$location is the object with Latitude and Longitude value.