Under Laravel 5 i'm trying to send mail for user with this below route :
Route::post('/sendEmailToUser', array(
'as' => 'sendEmailToUser', function () {
$data = \App\User::find(Request::input('user_id'));
$cdata = array('message' => Request::input('message'), 'email' => $data->email);
Mail::send('emails.custom_email_to_user', $cdata, function ($message) use ($data) {
$message->to($data['email'], 'Sample')->subject('Sample');
});
if (count(Mail::failures()) > 0) {
Log::emergency("email dont send to user");
return 0;
} else {
Log::info("email successfull send to user id" + Request::input('user_id'));
return 1;
}
}
));
Result of $cdata is :
Array
(
[message] => this is test mail
[email] => myname#server.com
)
Unfortunately i get this error :
htmlentities() expects parameter 1 to be string, object given (View: D:\xampp\htdocs\epay-pro\resources\views\emails\custom_email_to_user.blade.php)
My simple email page is:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Sample</h2>
<div>
{{$message}}
{{ URL::to('www.epay.li') }}<br/>
</div>
</body>
</html>
You have to change two things in your code and it will work.
First : (choose how to use your variable $data)
You're using same variable $data sometimes as array and sometimes as object :
As object in :
$cdata = array('message' => Request::input('message'), 'email' => $data->email);
As array in :
$message->to($data['email'], 'Sample')->subject('Sample');
Normally you should use it as object since User::find will return an object.
Note : if you want to use it as array you have just to add toArray() after find.
Second : (change variable $message name)
Note: A $message variable is always passed to e-mail views, and allows the inline embedding of attachments. So, you should avoid passing a message variable in your view payload.
Source : Document laravel 5.1 - mail#introduction
So you have to change $message variable name because Framework will consider it as an Object of class Illuminate\Mail\Message.
Take a look to the following discution about the problem Laravel Mailing Issue "Object of class Illuminate\Mail\Message could not be conv...
Hope this helps.
While sending email $message variable seems to be conflicted with the laravels $message variable, i am not quite sure why. In your $cdata instead of message key use something else like maybe $text
$cdata = array('text' => Request::input('message'), 'email' => $data->email);
Related
I have a controller which passes an array data to view. Inside the view, I wanted to use the data as string in JSON object format.
Here is my controller:
class TestController extends Controller
{
private $user;
public function index()
{
return view('app')->with([
'userdata' => array('user' => 'John', 'age' => 20),
'access_token' => 'token_here'
]);
}
}
Here is my view app.php
<html>
<-- more html codes--->
<script>
let userdata = "{{ $userdata }}"; // ERROR: htmlspecialchars() expects parameter 1 to be string, array given
</script>
<-- more html codes--->
</html>
I tried using implode,
<script>
let userdata = "{{ implode(' ', $userdata)";
console.log(userdata);
</script>
It didn't have an error, but the problem is, the result becomes:
{"userdata":{"user" .....}
How can I have a correct result like this:
{'userdata': {'user':'john', 'age': 20}...} // this should be a string
Does anybody know?
You can use json_encode:
{!! json_encode($userdata) !!}
note that you have to use {!! !!} to get exact string what you want. strings placed in {{ }} are escaped
Also you can user blade directive #json . depends which version of laravel you are using:
#json($userdata)
From Laravel blade docs.
Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the #json Blade directive. The #json directive accepts the same arguments as PHP's json_encode function:
<script>
var app = #json($array);
var app = #json($array, JSON_PRETTY_PRINT);
</script>
I'm middle of practice laravel , basic lesson 11th on laracast, wondering that if I create an entity from form page like below
<html> blahblah..
..
<form method="post" action="{{ Route('customModel.store') }}">
forms.. many forms..
</form>
..
</html>
When I submit this form, data will flow through the router.
Route::post('/customModel', [
'as'=>'customModel.store',
'uses'=>'CustomModelController#store
]);
The CustomModelController has its method named store and problem is here..
public function store( Request $request )
{
$CustomModel = CustomModel::create([
'name' => Request('name'),
'desc' => Request('desc')
]);
// Here is the PROBLEMMMM..
return redirect('/field/'. $CustomModel->id );
}
It feels really... mm... weird using redirect function directly and attach some variables directly to fill wildcard value.
Is there other ways to replace redirect()?
Something like do something with Route or another?
You can also use route() method of Illuminate\Routing\Redirector class as:
return redirect()->route('route_name', ['id' => $id]);
Say,i have two form in one page.I have included one error blade file bellow both of the form. Now when i make wrong in one form & submit it the error message is showing bellow the both form.Its normal.But my question is, how do i separate this two error message,how can i differentiate by giving them two different name?
Give this a try
return redirect()->back()->withErrors([
'form1.name' => 'name is required in Form 1',
'form1.email' => 'email is required in Form 1',
'form2.city' => 'city is required in form 2'
]);
in your view
#if($errors->any())
#foreach ($errors->get('form1.*') as $error) {
{{ $error }}
#endforeach
#endif
So you can group errors by form using array notation form.name and get all with $errors->get('form.*).
Read more about errors here: https://laravel.com/docs/5.4/validation#working-with-error-messages
If you're using Form Request Validation, you can change the errorBag property to get a unique array of errors for your view file.
In your Request file:
class MyFormRequest {
protected $errorBag = 'foobar';
public function rules() { // ... }
}
In your controller:
public function store(MyFormRequest $request) {
// Store entry.
}
Then in your view file:
#if ($errors->foobar->isNotEmpty())
// Work with the errors
#endif
You can use the named error bags.
$validator = Validator::make($request->all(), [
'field1' => 'required',
'field2' => 'required|digits:1',
]);
if ($validator->fails()) {
return back()
->withErrors($validator, 'form1error')
->withInput();
}
To print the error in blade file use-
#if(count($errors->form1error)>0)
<ul>
#foreach($errors->form1error->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
This is the problem:
The name associated with the email shows up as "Example"
In config/mail.php
set from property as:
'from' => ['address' => 'someemail#example.com', 'name' => 'Firstname Lastname']
Here, address should be the one that you want to display in from email and name should be the one what you want to display in from name.
P.S. This will be a default email setting for each email you send.
If you need to use the Name as a variable through code, you can also call the function from() as follows (copying from Brad Ahrens answer below which I think is good to mention here):
return $this
->from($address = 'noreply#example.com', $name = 'Sender name')
->subject('Here is my subject')
->view('emails.view');
You can use
Mail::send('emails.welcome', $data, function($message)
{
$message->from('us#example.com', 'Laravel');
$message->to('foo#example.com')->cc('bar#example.com');
});
Reference - https://laravel.com/docs/5.0/mail
A better way would be to add the variable names and values in the .env file.
Example:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=example#example.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="My Name"
MAIL_FROM_ADDRESS=support#example.com
Notice the last two lines. Those will correlate with the from name and from email fields within the Email that is sent.
In the case of google SMTP, the from address won't change even if you give this in the mail class.
This is due to google mail's policy, and not a Laravel issue.
Thought I will share it here.
For anyone who is using Laravel 5.8 and landed on this question, give this a shot, it worked for me:
Within the build function of the mail itself (not the view, but the mail):
public function build()
{
return $this
->from($address = 'noreply#example.com', $name = 'Sender name')
->subject('Here is my subject')
->view('emails.welcome');
}
Happy coding :)
If you want global 'from name' and 'from email',
Create these 2 keys in .env file
MAIL_FROM_NAME="global from name"
MAIL_FROM_ADDRESS=support#example.com
And remove 'from' on the controller. or PHP code if you declare manually.
now it access from name and from email.
config\mail.php
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'info#example.com'),
'name' => env('MAIL_FROM_NAME', 'write name if not found in env'),
],
ON my controller.
$conUsBody = '';
$conUsBody .= '<h2 class="text-center">Hello Admin,</h2>
<b><p> '.trim($request->name).' Want some assesment</p></b>
<p>Here are the details:</p>
<p>Name: '.trim($request->name).'</p>
<p>Email: '.trim($request->email).'</p>
<p>Subject: '.trim($request->subject).'</p>';
$contactContent = array('contactusbody' => $conUsBody);
Mail::send(['html' => 'emails.mail'], $contactContent,
function($message) use ($mailData)
{
$message->to('my.personal.email#example.com', 'Admin')->subject($mailData['subject']);
$message->attach($mailData['attachfilepath']);
});
return back()->with('success', 'Thanks for contacting us!');
}
My blade template.
<body>
{!! $contactusbody !!}
</body>
I think that you have an error in your fragment of code. You have
from(config('app.senders.info'), 'My Full Name')
so config('app.senders.info') returns array.
Method from should have two arguments: first is string contains address and second is string with name of sender. So you should change this to
from(config('app.senders.info.address'), config('app.senders.info.name'))
While trying to send verification email using Laravel 5.2, I get an error:
Undefined variable: confirmation_code (View:
C:\xampp\htdocs\laravel\resources\views\email\verify.blade.php)
My code looks like this:
Controller.php:
public function postSignup(Request $request){
$this->validate($request,[
'email'=>'required|unique:users|email',
'name'=>'required|max:50|min:3',
'password'=>'required|min:6',
'con-password'=>'required|same:password',
]);
$confirmation_code=['code'=>str_random(20)];
$name = $request->input('name');
Mail::send('email.verify',$confirmation_code,function($message)
use($request,$name){
$message->to($request->input('email'),$name)
->subject('Verify Your Email Address');
});
User::create([
'email'=>$request->input('email'),
'name'=>$request->input('name'),
'password'=>bcrypt($request->input('password'))
]);
return redirect()->back()->with('info','Congratulation you have been successfully registered.Please check your email for verification');
}
Mail.verify.blade.php:
<h2>Verify Your Email Address</h2>
<div>
Thanks for creating an account with the verification demo app.
Please follow the link below to verify your email address
{{ URL::to('register/verify/'.$confirmation_code) }}.<br/>
</div>
</body>
Try this:
Mail::send('email.verify', compact('confirmation_code'), function ($message) use($request, $name) {
$message->to($request->input('email'),$name)
->subject('Verify Your Email Address');
});
The reason why it fails is that Laravel views accept an associative array as their data, so that it can turn them into variables using keys as variables names and match them to their corresponding values.
What compact does is turn your variable into an associative array, with the name of the variable as its key (sort of the opposite of what the Laravel view will do).