so i was trying to send a mail with a pdf attachment but i get this error No hint path defined for [mail].
here is my buld function syntax
public function build()
{
$pdf = $this->pdf;
return $this->subject("Transaction Request")
->from('finance#vcass.org')
->attachData($pdf, 'transaction.pdf', [
'mime' => 'application/pdf'
])
->markdown('emails.usersingle', ['transaction' => $this->transaction]);
}
and here is my controller code
public function sendtransaction(Request $request)
{
$data = $request->all();
$id = $data['id'];
$transaction = Transaction::find($id);
$pdf = PDF::loadView('emails.usersingle', compact('transaction'));
$pdf = $pdf->output();
try {
Mail::to($data['email'])->send(new MailTransaction($transaction, $pdf));
return redirect()->back()->with('success', 'transaction sent to mail, check your mail');
} catch (\Swift_TransportException $e) {
return redirect()->back()->with('warning', 'Sorry mail couldnt be sent, please try again');
} catch (\Exception $e) {
dd($e);
}
}
please I need help on this fast!
I am currently working on a paypal checkout using paypal and https://github.com/srmklive/laravel-paypal. I'm using the express checkout which I modified it a little bit to fit the requirements of the my project. During testing it is working in a couple of tries, paypal show and payment executes properly but when I tried to run the exact same code. I get this error I don't know what it means.
I tried to check my routes if it all of the errors happens to my routes but all of it are working properly. I also tried dump and die like dd("check") just to check if its really going to my controller and it does. I did this in the method "payCommission" (this where the I think the error happens)
This is my route for the controller
api.php
Route::get('service/commissionfee/payment' , 'api\service\ExpressPaymentController#payCommission');
Route::get('paypal/ec-checkout-success', 'api\service\ExpressPaymentController#payCommissionSuccess');
ExpressPaymentController.php
<?php
namespace App\Http\Controllers\api\service;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Srmklive\PayPal\Services\ExpressCheckout;
class ExpressPaymentController extends Controller
{
protected $provider;
public function __construct()
{
try {
$this->provider = new ExpressCheckout();
}
catch(\Exception $e){
dd($e);
}
}
public function payCommission(Request $request)
{
$recurring = false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
dd($e);
return response()->json(['code' => 'danger', 'message' => "Error processing PayPal payment"]);
}
}
public function payCommissionSuccess(Request $request)
{
$recurring = false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// ? Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], 9.99, $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// ? Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
return response()->json(['success' => "payment complete"]);
}
}
private function getCheckoutData($recurring = false)
{
$data = [];
$order_id = 1;
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'qty' => 1,
],
];
$data['return_url'] = url('api/paypal/ec-checkout-success');
// !
$data['invoice_id'] = config('paypal.invoice_prefix').'_'.$order_id;
$data['invoice_description'] = "Commission Fee payment";
$data['cancel_url'] = url('/');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
}
Error I am getting
Object of class Illuminate\Routing\Redirector could not be converted to string
Thank you in advance
you may just go to the config/paypal.php and edit
'invoice_prefix' => env('PAYPAL_INVOICE_PREFIX', 'Life_saver_'),
you may use _ underline in this like Life_saver_, dont forget use underline at the end too.
I'm totally new to GraphQL and wanted to play arouund with graphql-php in order to build a simple API to get started. I'm currently reading the docs and trying out the examples, but I'm stuck quite at the beginning.
I want my schema to be stored in a schema.graphql file instead of building it manually, so I followed the docs on how to do that and it is indeed working:
<?php
// graph-ql is installed via composer
require('../vendor/autoload.php');
use GraphQL\Language\Parser;
use GraphQL\Utils\BuildSchema;
use GraphQL\Utils\AST;
use GraphQL\GraphQL;
try {
$cacheFilename = 'cached_schema.php';
// caching, as recommended in the docs, is disabled for testing
// if (!file_exists($cacheFilename)) {
$document = Parser::parse(file_get_contents('./schema.graphql'));
file_put_contents($cacheFilename, "<?php\nreturn " . var_export(AST::toArray($document), true) . ';');
/*} else {
$document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well
}*/
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
// In the docs, this function is just empty, but I needed to return the $typeConfig, otherwise I got an error
return $typeConfig;
};
$schema = BuildSchema::build($document, $typeConfigDecorator);
$context = (object)array();
// this has been taken from one of the examples provided in the repo
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
$rootValue = ['prefix' => 'You said: '];
$result = GraphQL::executeQuery($schema, $query, $rootValue, $context, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
This is what my schema.graphql file looks like:
schema {
query: Query
}
type Query {
products: [Product!]!
}
type Product {
id: ID!,
type: ProductType
}
enum ProductType {
HDRI,
SEMISPHERICAL_HDRI,
SOUND
}
I can query it for example with
query {
__schema {types{name}}
}
and this will return the metadata as expected. But of course now I want to query for actual product data and get that from a database, and for that I'd need to define a resolver function.
The docs at http://webonyx.github.io/graphql-php/type-system/type-language/ state: "By default, such schema is created without any resolvers. We have to rely on default field resolver and root value in order to execute a query against this schema." - but there is no example for doing this.
How can I add resolver functions for each of the types/fields?
This approach works without instantiating a Server. In my case, I already have a server and can read HTTP data, all I needed was to read the GraphQL schema and run the query. First I read the schema from a file:
$schemaContent = // file_get_contents or whatever works for you
$schemaDocument = GraphQL\Language\Parser::parse($schemaContent);
$schemaBuilder = new GraphQL\Utils\BuildSchema($schemaDocument);
$schema = $schemaBuilder->buildSchema();
Then I execute the query passing a custom field resolver:
$fieldResolver = function() {
return call_user_func_array([$this, 'defaultFieldResolver'], func_get_args());
};
$result = GraphQL\GraphQL::executeQuery(
$schema,
$query, // this was grabbed from the HTTP post data
null,
$appContext, // custom context
$variables, // this was grabbed from the HTTP post data
null,
$fieldResolver // HERE, custom field resolver
);
The field resolver looks like this:
private static function defaultFieldResolver(
$source,
$args,
$context,
\GraphQL\Type\Definition\ResolveInfo $info
) {
$fieldName = $info->fieldName;
$parentType = $info->parentType->name;
if ($source === NULL) {
// this is the root value, return value depending on $fieldName
// ...
} else {
// Depending on field type ($parentType), I call different field resolvers.
// Since our system is big, we implemented a bootstrapping mechanism
// so modules can register field resolvers in this class depending on field type
// ...
// If no field resolver was defined for this $parentType,
// we just rely on the default field resolver provided by graphql-php (copy/paste).
$fieldName = $info->fieldName;
$property = null;
if (is_array($source) || $source instanceof \ArrayAccess) {
if (isset($source[$fieldName])) {
$property = $source[$fieldName];
}
} else if (is_object($source)) {
if (isset($source->{$fieldName})) {
$property = $source->{$fieldName};
}
}
return $property instanceof \Closure
? $property($source, $args, $context)
: $property;
}
}
Here's what I ended up doing...
$rootResolver = array(
'emptyCart' => function($root, $args, $context, $info) {
global $rootResolver;
initSession();
$_SESSION['CART']->clear();
return $rootResolver['getCart']($root, $args, $context, $info);
},
'addCartProduct' => function($root, $args, $context, $info) {
global $rootResolver;
...
return $rootResolver['getCart']($root, $args, $context, $info);
},
'removeCartProduct' => function($root, $args, $context, $info) {
global $rootResolver;
...
return $rootResolver['getCart']($root, $args, $context, $info);
},
'getCart' => function($root, $args, $context, $info) {
initSession();
return array(
'count' => $_SESSION['CART']->quantity(),
'total' => $_SESSION['CART']->total(),
'products' => $_SESSION['CART']->getProductData()
);
},
and then in the config
$config = ServerConfig::create()
->setSchema($schema)
->setRootValue($rootResolver)
->setContext($context)
->setDebug(DEBUG_MODE)
->setQueryBatching(true)
;
$server = new StandardServer($config);
It feels rather hack-ish to me, and I should probably outsource the resolvers into separate files, but it works... Still baffled that there are no simple examples for this task, maybe in an even better way than my solution...
I'm using root value for this:
<?php
require("vendor/autoload.php") ;
require("exemplo-graphql.php");
require("Usuario.php");
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use GraphQL\Utils\BuildSchema;
$query = $_REQUEST['query'];
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
$name = $typeConfig['name'];
// ... add missing options to $typeConfig based on type $name
return $typeConfig;
};
$contents = file_get_contents('schema.graphql');
$schema = BuildSchema::build($contents, $typeConfigDecorator);
// $rawInput = file_get_contents('php://input');
$input = json_decode($query, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
// $rootValue = ['prefix' => 'You said: '];
$rootValue = [
'usuario' => function($root, $args, $context, $info) {
$usuario = new Usuario();
$usuario->setNome("aqui tem um teste");
$usuario->setEmail("aqui tem um email");
return $usuario;
},
'echo' => function($root, $args, $context, $info) {
return "aqui tem um echooo";
},
'adicionarUsuario' => function ($root, $args, $context, $info) {
$usuario = new Usuario();
$usuario->setNome("aqui tem um teste");
$usuario->setEmail("aqui tem um email");
return $usuario;
}
];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null,
$variableValues);
if ($result->errors) {
$output = [
'errors' => [
[
'message' => $result->errors
]
]
];
} else {
$output = $result->toArray();
}
} catch (\Exception $e) {
$output = [
'errors' => [
[
'message' => $e->getMessage()
]
]
];
}
header('Content-Type: application/json');
echo json_encode($output);
By default, schema which was created by using BuildSchema::build() was created without any resolvers. So we need to define our custom resolvers as follows:
$contents = file_get_contents($this->projectDir.'/config/schema.graphql');
$typeConfigDecorator = function($typeConfig, $typeDefinitionNode) {
$name = $typeConfig['name'];
if ($name === 'Query') {
$typeConfig['resolveField'] =
function ($source, $args, $context, ResolveInfo $info) {
if ($info->fieldDefinition->name == 'login') {
if ($args['userName'] === 'test' && $args['password'] === '1234') {
return "Valid User.";
} else {
return "Invalid User";
}
} elseif ($info->fieldDefinition->name == 'validateUser') {
if ($args['age'] < 18) {
return ['userId' => $args['userId'], 'category' => 'Not eligible for voting'];
}
}
}
}
;
}
return $typeConfig;
};
$schema = BuildSchema::build($contents, $typeConfigDecorator);
The above example I have added resolvers for my two queries namely 'login' and 'validateUser.'
No need to define any root values and defaultFieldResolver. Our custom resolvers are enough.
New to laravel4 and cant get the basic things to work such as:
function doRegister() {
try {
$email = Input::get('email');
$type = Input::get('type'); // <-- Data from radio button
# Check if email exists
if ( User::where('email','=',$email)->count() > 0 ) {
# This account already exists
throw new Exception( 'This email already in use by someone else.' );
}
} catch (Exception $e) {
return Redirect::to('/')->withInput()->with('message', $e->getMessage() );
}
}
Now on the homepage controller (which is /) I cant read the value of Input::old('type');
and it returns empty. How come?
Try this instead:
function doRegister()
{
$rules = array('email' => 'required|email|unique:users');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('/')->withInput()>withErrors($validator);
}
else {
$email = Input::get('email');
$type = Input::get('type');
// Register...
}
}
You can retrieve validation errors using:
$errors->first('email');
I am hoping someone has some experience with the blueimp fileupload jquery plugin at : https://github.com/blueimp/jQuery-File-Upload
How to add the uploaded file name to database ?
In the options array (look for $this->options = array( )
and insert
'database' => 'database_name',
'host' => 'localhost',
'username' => 'user',
'password' => 'password',
Then after
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = new stdClass();
$file->name = $this->get_file_name($name, $type, $index, $content_range);
$file->size = $this->fix_integer_overflow(intval($size));
$file->type = $type;</code></pre>
Insert this code
//Start added coded
// prepare the image for insertion
$data = addslashes (file_get_contents($uploaded_file));
// get the image info..
$size = getimagesize($uploaded_file);
$file->upload_to_db = $this->add_img($data, $size, $name);
//end added code
and after the function handle_file_upload insert the following code to actually upload the image to the database.
function query($query) {
$database = $this->options['database'];
$host = $this->options['host'];
$username = $this->options['username'];
$password = $this->options['password'];
$link = mysql_connect($host,$username,$password);
if (!$link) {
die(mysql_error());
}
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die(mysql_error());
}
$result = mysql_query($query);
mysql_close($link);
return $result;
}
function add_img($data,$size,$name)
{
$add_to_db = $this->query("INSERT INTO your_database_name
(image_type ,image, image_size, file_name)
VALUES
('{$size['mime']}', '{$data}', '{$size[3]}', '{$name}')") or die(mysql_error());
return $add_to_db;
}
This will store the actual image in the database if you don't want that change the add_img($data,$size,$name) to add_img($size,$name) and just don't pass the $data variable. The $data variable should be stored as a medium or long blob.
You can also comment out the fileupload to directory stuff so you don't get errors if you don't what the images uploaded to a directory. This is in the protected function handle_file_upload
//comment out file upload stuff since storing in database
/*
if ($this->validate($uploaded_file, $file, $error, $index)) {
$this->handle_form_data($file, $index);
$upload_dir = $this->get_upload_path();
if (!is_dir($upload_dir)) {
mkdir($upload_dir, $this->options['mkdir_mode'], true);
}
$file_path = $this->get_upload_path($file->name);
$append_file = $content_range && is_file($file_path) &&
$file->size > $this->get_file_size($file_path);
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
if ($append_file) {
file_put_contents(
$file_path,
fopen($uploaded_file, 'r'),
FILE_APPEND
);
} else {
move_uploaded_file($uploaded_file, $file_path);
}
} else {
// Non-multipart uploads (PUT method support)
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
}
$file_size = $this->get_file_size($file_path, $append_file);
if ($file_size === $file->size) {
$file->url = $this->get_download_url($file->name);
list($img_width, $img_height) = #getimagesize($file_path);
if (is_int($img_width) &&
preg_match($this->options['inline_file_types'], $file->name)) {
$this->handle_image_file($file_path, $file);
}
} else {
$file->size = $file_size;
if (!$content_range && $this->options['discard_aborted_uploads']) {
unlink($file_path);
$file->error = 'abort';
}
}
$this->set_additional_file_properties($file);
}
*/