Why am I getting "Undefined variable: emails" in Laravel 5.4, but the same code is working fine in Laravel 5.2? Below is a code snipped. Don't think this matters but I'm using PHP 7.1.3.
public function send(Request $request) {
$emails = "";
try {
$emails = [$request->input('to'), "john.doe#gmail.com"];
Mail::send('email.contact', ['request' => $request], function($message) use ($request) {
$message->from($request->input('email'), $request->input('email'));
$message->to($emails[0], $emails[0])
->cc($emails[1], $emails[1])
->subject("Contact Us");
});
$response = array (
'success' => true,
'message' => 'Message sent.',
$request
);
}
catch(Exception $e) {
$response = array (
'success' => false,
'message' => $e->getMessage(),
$request
);
}
// return Response::json( $response );
return $response;
}
The issue is here:
use ($request) {
to use $emails inside the anonymous function you have to pass it here like:
use ($request, $emails) {
Now you can use it.
Anonymous function reference
Just simply use the $emails variable in the anonymous function along with $request variable.
Full code to give this it a try.
public function send(Request $request) {
$emails = "";
try {
$emails = [$request->input('to'), "john.doe#gmail.com"];
Mail::send('email.contact', ['request' => $request], function($message) use ($request, $emails) {
# Here add $emails variable in use list.
$message->from($request->input('email'), $request->input('email'));
$message->to($emails[0], $emails[0])
->cc($emails[1], $emails[1])
->subject("Contact Us");
});
$response = array (
'success' => true,
'message' => 'Message sent.',
$request
);
}
catch(Exception $e) {
$response = array (
'success' => false,
'message' => $e->getMessage(),
$request
);
}
// return Response::json( $response );
return $response;
}
Hope this helps.
Related
I have a Laravel 8 project. I want to change magic auth error message. And I did updated my code like this.
'This code has already been used' I replaced this message with this in the context of the code 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.'
OLD AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'This code has already been used.']);
}
return redirect()->route('login');
}
NEW AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.']);
}
return redirect()->route('login');
}
But when I try now, I see that the message has not changed. How can I fix this?
Please follow below steps:
If you haven't done it yet, delete or rename the old AuthController class, use only new one, with new message.
Make sure routes going to the methods in the new controller
Run composer dump-autoload.
If the problem still persist I'd check whether some kind of cache mechanism is enabled in php, like opcache.
I cannot get a URL varible in my stripe checkout PHP slim app.
I need to be able to get a price varible from the URL to echo out into the session for the price of stripe payment. However it is just not working, I can use $_GET['price']; to echo out before it becomes a SLIM APP however when it becomes a SLIM APP it just wont work...
use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::create(realpath('../../'));
$dotenv->load();
Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
$db = new SQLite3('./store.db');
$db->exec("CREATE TABLE IF NOT EXISTS sessions(id INTEGER PRIMARY KEY, stripe_id TEXT, status TEXT)");
// createSession
function createSession($sessionId) {
global $db;
$stmt = $db->prepare("INSERT INTO sessions(stripe_id, status) VALUES (:id, 'pending')");
$stmt->bindValue(':id', $sessionId, SQLITE3_TEXT);
return $stmt->execute();
}
// markSessionPaid
function markSessionPaid($sessionId) {
global $db;
$stmt = $db->prepare("UPDATE sessions SET status='paid' WHERE :id = stripe_id");
$stmt->bindValue(':id', $sessionId, SQLITE3_TEXT);
return $stmt->execute();
}
// getSessionStatus
function getSessionStatus($sessionId) {
global $db;
$stmt = $db->prepare("SELECT status FROM sessions WHERE :id = stripe_id");
$stmt->bindValue(':id', $sessionId, SQLITE3_TEXT);
$result = $stmt->execute();
return $result->fetchArray()[0];
}
$app = new Slim\App;
$app->get('/', function (Request $request, Response $response, $args) {
$response->getBody()->write(file_get_contents("../../client/index.html"));
return $response;
});
$app->get('/success', function (Request $request, Response $response, $args) {
$response->getBody()->write(file_get_contents("../../client/success.html"));
return $response;
});
$app->get('/cancel', function (Request $request, Response $response, $args) {
$response->getBody()->write(file_get_contents("../../client/cancel.html"));
return $response;
});
function middleware1() {
$price = $app->request()->get('price');
};
$app->post('/create-session', 'middleware1', function(Request $request, Response $response) use ($app) {
try {
// One time payments
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'name' => 'Order',
'description' => 'ORDER ID: 123456789A',
'images' => ['testimage'],
'amount' => $price,
'currency' => 'aud',
'quantity' => 1,
]],
'success_url' => 'http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'http://localhost:4242/cancel',
]);
// Subscription recurring payments
// $session = \Stripe\Checkout\Session::create([
// // 'customer' => 'cus_123',
// 'payment_method_types' => ['card'],
// 'subscription_data' => [
// 'items' => [[
// 'plan' => 'starter',
// 'quantity' => 1,
// ]],
// ],
// 'success_url' => 'http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}',
// 'cancel_url' => 'http://localhost:4242/cancel',
// ]);
createSession($session->id);
} catch (Exception $e) {
return $response->withJson($e->getJsonBody(), 400);
}
return $response->withJson($session);
});
$app->post('/webhook', function(Request $request, Response $response) use ($app) {
// You can find your endpoint's secret in your webhook settings
$endpoint_secret = getenv('STRIPE_WEBHOOK_SECRET');
$payload = $request->getBody();
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400);
exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
// Handle the checkout.session.completed event
if ($event->type == 'checkout.session.completed') {
$session = $event->data->object;
// Fulfill the purchase...
handle_checkout_session($session);
}
return $response->withJson(['message' => 'success']);
});
$app->get('/session-status', function (Request $request, Response $response, array $args) {
$status = getSessionStatus($request->getQueryParam('session_id'));
return $response->withJson($status);
});
function handle_checkout_session($session) {
// Call out to inventory management system
// Ding in Slack
// send an email
markSessionPaid($session->id);
}
$app->run();
I've tried everything
$app->request()->get('price');
And more!
The URL looks like this www.example.com/server/php/?price=5770&orderid=y2INOqCUrEzrua1XwBMg
Any help would be greatly appreciated!
You cannot use $_GET in Slim since it wont work. One way to do it is since the parameters are passed in query I think you mean it like this checkout/?price=200. If so, then you can access it using this:
$queryParams = $app->request()->getQueryParams();
$price = $queryParams["price"];
This would probably work
I am building a API using laravel, and i am trying to create a function to find a user in data base using a email as a parameter
public function find_user(Request $request){
try{
$user = UserAccess::table('user_accesses')->where('email', $request->email)->first();
return ['api_request_return'=>'ok', 'return' => $user];
}catch(\Exception $error){
return ['api_request_return' => 'error', 'error_details' => $error];
}
}
The API route is ok, but its always returning error:
{
"api_request_return": "error",
"error_details": {}
}
Use the corrected one
public function find_user(Request $request){
try{
$user = DB::table('user_accesses')->where('email', $request->email)->first();
return ['api_request_return'=>'ok', 'return' => $user];
}catch(\Exception $error){
return ['api_request_return' => 'error', 'error_details' => $error];
}
}
I'm making a custom fuction on my Model to check if a user belongs to a external api list.
public function mailchimp()
{
$mailchimp = new Client(['base_uri' => 'https://us14.api.mailchimp.com/3.0/']);
try
{
$checkEmail = $mailchimp->request('GET', 'lists/768ce70724/members/' . md5($this->email), [
'headers' => [ 'Authorization' => 'apikey ' . config('globals.mailchimp_key') ]
]);
}
catch( \Exception $exception ) {
//if ( $exception->getResponse()->getStatusCode() === 404) { return 'not a subscriber'; }
return 'error'; // where the error occurs
}
$result = json_decode( $checkEmail->getBody() );
//return $result->status;
return 'success';
}
This is how I call the method:
$emails = $newsletter
->with('user')
->with('mailchimp')
->paginate(config('globals.results_per_page'));
return $emails;
Error: http://prntscr.com/dbm2ts
When you're usng with() Laravel is trying to load a relation. So, mailchimp() should be a relation here.
I was unable to go to the method on the controller but I managed to access it from the view which works well!
I created a simple mail sender. The problem is [1]
[1]: http://i.stack.imgur.com/uJHmB.png here. ı can't add the contacts names at the mail. Plase help me.
My mail send controller.
public function sendMail($id) {
$compaign = Compaign::findOrFail($id);
$group = Group::findOrFail($compaign->group);
$contacts = Contact::all()->where('group', $group->id);
if($contacts->count() <= 0) {
Session::flash('error', 'No recipients found!');
return redirect()->route('compaign.index');
}
foreach ($contacts as $contact) {
$data = [
'compaign' => $compaign,
'group' => $group,
'contact' => $contact,
];
Mail::send('mail', $data, function ($message) use ($data) {
$message->from($data['compaign']->femail, $data['compaign']->fname);
$message->to($data['contact']->email, $data['contact']->name)->subject($data['compaign']->subject);
});
}
Session::flash('success', 'Successfully sent the campaign');
return redirect()->route('compaign.index');
}
my mail.blade.php
{!!$compaign->content!!}
In your controller:
Mail::send('mail',array('compaign' => $data), ($message) use ($data) {
$message->from($data['compaign']->femail, $data['compaign']->fname);
$message->to($data['contact']->email, $data['contact']->name)->subject($data['compaign']->subject);
});
This should work:
public function sendMail($id)
{
$compaign = Compaign::findOrFail($id);
$group = Group::findOrFail($compaign->group);
$contacts = Contact::where('group', $group->id)->get();
if( ! $contacts->count()) {
Session::flash('error', 'No recipients found!');
return redirect()->route('compaign.index');
}
$data = [
'compaign' => $compaign,
'group' => $group,
'contacts' => $contacts
];
foreach ($contacts as $contact) {
Mail::send('mail', $data, function ($message) use ($compaign, $contact) {
$message->from($compaign->femail, $compaign->fname);
$message->to($contact->email, $contact->name);
$message->subject($compaign->subject);
});
}
Session::flash('success', 'Successfully sent the campaign');
return redirect()->route('compaign.index');
}
in blade
#foreach($contacts as $contact)
{!! $contact->email !!}
{!! $compaign-fname !!}
#endforeach
If not please dump the $compaign and $contacts variables.