sending random ids - Laravel email - php

Good day
I'm using Mailgun to send emails to the users with required info from the order after submitting the form,I managed to send the subject and the email address ,but I'm having trouble sending the random number that gets assigned on the creation of the order.
here is my controller:
public function store(Request $request)
{
$order = $user->orders()->create([
'randomid' => rand(100000,999999),
'subject' => $request->get('subject'),
'email' => $request->get('email'),
]);
$data = $request->only('subject', 'email', 'randomid');
Mail::send('emails.note',
$data
, function($message) use ($data)
{
$message->subject('New Order: '.$data['subject'])
->from('myemail#myserver.com')
->to($data['email']);
});
}

I saw that you get the $data from request object
$data = $request->only('subject', 'email', 'randomid');
but randomid was generated in created method
$order = $user->orders()->create([
'randomid' => rand(100000,999999),
'subject' => $request->get('subject'),
'email' => $request->get('email'),
]);
So there is not randomid in request.
I think you should get $data from $order like the folowing:
$data = $order->toArray();
So You will have:
public function store(Request $request)
{
$order = $user->orders()->create([
'randomid' => rand(100000,999999),
'subject' => $request->get('subject'),
'email' => $request->get('email'),
]);
$data = $order->toArray();
Mail::send('emails.note',
$data
, function($message) use ($data)
{
$message->subject('New Order: '.$data['subject'])
->from('myemail#myserver.com')
->to($data['email']);
});
}

The randomid doesn't come from the request. You generate its value manually using rand(100000,999999) !
Please try this:
public function store(Request $request){
$data = [
'randomid' => rand(100000, 999999) ,
'subject' => $request->input('subject') ,
'email' => $request->input('email')
];
$order = $user->orders()->create($data);
Mail::send('emails.note', $data, function ($message) use($data) {
$message->subject('New Order: ' . $data['subject'])
->from('myemail#myserver.com')->to($data['email']);
});
}

Related

Why would the update produce this result ` {"email":"try#gmail.com"}` in the database

when i try to update email column for the user i get a weird input in the database and i don't see why. The output in the email column in the database looks something like this {"email":"try#gmail.com"} instead of just the email
HomeController
protected function createMail(Request $request)
{
$data = request()->validate([
'email' => 'required',
]);
$id = Auth::guard('web')->id();
User::where('id', $id)->update(['email' => $data]);
}
$data in your case is defined as a result of ->validate() function, but you need the value of email.
Value can be accessed with $request->get('email').
so your function should look like this:
protected function createMail(Request $request)
{
$this->validate($request, [
'email' => 'required',
]);
$id = Auth::guard('web')->id();
User::where('id', $id)->update(['email' => $request->get('email')]);
}
you are updating wrong value and it should be like this
protected function createMail(Request $request)
{
$this->validate($request, [
'email' => 'required',
]);
$id = Auth::guard('web')->id();
User::where('id', $id)->update(['email' => $request->get('email')]);
}
as you see request->get('email') instead of ['email' => $data]

Exclude a validated array object from inserting into db

I'm trying to exclude an object from an array from inserting into a database only after validation. The code sample is below
public function store(Request $request)
{
//
$request->merge([
'added_by' => auth('api')->user()->id,
]);
$travel = TravelSummary::create( $this->validateRequest($id = null) );
event(new TravelRequestCreatedEvent($travel, $action = 'added travel request'));
return (new TravelSummaryResource($travel))
->response()
->setStatusCode(Response::HTTP_CREATED);
}
Below is the array of validated fields
private function validateRequest($id){
return request()->validate([
'travel_request_no' => $id ? 'required' : 'required|unique:travel_summaries',
'purpose' => 'required',
'total' => 'nullable',
'cash_advance' => 'nullable',
'advance_amount' => 'nullable|lte:total',
'added_by' => 'required'
]);
}
Can the total be excluded only after validation?
use
$data = $request->only(['travel_request_no', 'purpose', 'cash_advance', 'advance_amount', 'advance_amount']);
or
$data = $request->except(['total']);
after validation then pass that data to create model. here is an example.
$this->validateRequest($id = null);
$data = $request->only(['travel_request_no', 'purpose', 'cash_advance', 'advance_amount', 'advance_amount']);
//or you can use except
//$data = $request->except(['total']);
$travel = TravelSummary::create($data);
You can unset the data you wish to exclude, after validation, like so:
// The validator will return the validated data as an array
$data = $this->validateRequest($id = null);
// This will remove the key and value from the array.
unset($data['total']);
$travel = TravelSummary::create($data);

Undefined variable in Lumen

I am going to send email using gmail smtp in lumen, Everything working fine but one variable is always undefined, Please let me know where i am wrong
Here is my code
<?php
namespace App\Services;
use Illuminate\Support\Facades\Mail;
class MailService
{
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}
}
Here is the Controller
public function register(Request $request)
{
$rules = [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:5',
'phone' => 'required|numeric|min:10',
'business_name' => 'required|unique:users',
'business_type' => 'required'
];
$this->validate($request, $rules);
$data = $request->all();
$hashPassword = Hash::make($data['password']);
$data['password'] = $hashPassword;
$data['is_activated'] = 'false';
$pin = mt_rand(1000, 9999);
$token = hash("sha256", $pin);
$data['token'] = $token;
$data['otp'] = $pin;
$user = User::create($data);
if ($user) {
MailService::send($request->input('email'), 'OTP', $pin);
return response()->json(['response' => true, 'message' => 'User registered Successfully', 'token' => $token], 201);
} else {
return response()->json(['response' => false, 'message' => ' Please check your credentials, Try again'], 400);
}
}
Here is the error
{message: "Undefined variable: mail_to", exception: "ErrorException", file: "D:\xampp\htdocs\api\app\Services\MailService.php", line: 12, trace: Array(28)}
exception: "ErrorException"
file: "D:\xampp\htdocs\api\app\Services\MailService.php"
line: 12
message: "Undefined variable: mail_to"
You are missing $mail_to. you need to use it in function then you may use it otherwise you would get an undefined variable error as you're getting it now.
use($mail_to)
Here your code looks like below.
public static function send($mail_to = '', $title = '', $content = '') {
Mail::send('mail', ['title' => $title, 'content' => $content], function ($message) use($mail_to) {
$message->from('noreply#gmail.com', 'Test Mail');
$message->to($mail_to);
});
}

Associate models with eachother Laravel

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();

Passing data to queued Mail object in Laravel 4, using Iron.io

I am trying to set up a queued email in Laravel 4 using the Iron.io driver. I would like to pass some details to the email's Subject and From attributes but they seem to not be making it into the queue request and their presence causes the email to not be sent (not sure where to look for a log with errors). However, simply using Mail::Send() works fine.
Here is the code in question:
public function handleFeedbackForm()
{
$data = array(
'name_f' => Input::get('name_f'),
'name_l' => Input::get('name_l'),
'email' => Input::get('email'),
'commentType' => Input::get('commentType'),
'testimonialPublish_answer' => Input::get('testimonialPublish_answer'),
'comment' => Input::get('message')
);
$rules = array(
'name_f' => 'required',
'name_l' => 'required',
'email' => 'required|email',
'message' => 'required'
);
$v = Validator::make(Input::all(), $rules);
if ($v->passes())
{
$emailInfo = array('name_f' => Input::get('name_f'),
'name_l' => Input::get('name_l'),
'email' => Input::get('email'));
Mail::queue('emails.feedback', $data, function($message) use($emailInfo)
{
$recipients = array();
$form = MailType::find(1);
foreach ($form->users as $user)
{
$recipients[] = $user->email;
}
if (count($recipients) == 0)
{
// Nobody for this field, send to webmaster
$recipients[] = 'someone#somewhere.com';
}
$message->to($recipients)
->from($emailInfo['email'])
->subject('Foobar Feedback Form Message - ' . $emailInfo['name_f'] . ' ' . $emailInfo['name_l']);
});
return Redirect::to('contact')->with('feedbackSuccess', true);
}
else
{
return Redirect::to('contact')->with('feedbackError', true);
}
}
Any ideas? Thanks!

Categories