i have error in my code, when running to send a data via email on laravel "Attempt to read property "email" on null".
Attempt to read property "email" on null
and this my EmailController: https://pastebin.com/UhHYQpNz
enter code here
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use App\Mail\HelloMail;
use App\Mail\ProductMail;
use App\Product;
class EmailController extends Controller
{
public function index()
{
return view('welcome');
}
public function dataEmail()
{
$products = Product::all();
return view('data-email', compact('products'));
}
public function send(Request $request)
{
Mail::to($request->email)->send(new HelloMail($request->body));
return back();
}
public function sendproductMail($id)
{
$product = Product::findOrFail($id);
Mail::to($product->costumer_email)->send(new ProductMail($product));
return back();
}
}
product-template: https://pastebin.com/TFiyiCCS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{asset('style/bootstrap.min.css')}}">
</head>
<body>
<div class="container">
<h1>Selamat</h1>
<p>
Anda telah membeli barang <strong> {{ $product->product_name }} </strong>
</p>
<p>Thank You</p>
<strong>Bakiak</strong>
</div>
<script src="{{asset('script/jquery-3.5.0.min.js')}}"></script>
<script src="{{asset('script/bootstrap.min.js')}}"></script>
</body>
</html>
ProductMail: https://pastebin.com/FymbCAfF
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ProductMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public $product;
public function __construct($product)
{
$this->product = $product;
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('product buy Successfully')
->view('mail.product-template');
}
}
Please help improve my code
Validate input field email
and body
before sending any mail.
use Illuminate\Support\Facades\Validator;
public function send(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|min:4|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
Mail::to($request->email)->send(new HelloMail($request->body));
return back();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.