In laravel 5.8 I have a report with a button “Send Email” by clicking on this button ajax request is run, with content of a report
in “report_html” var to control like:
public function sentReportEmailContent()
{
$request= request();
$requestData= $request->all();
$report_html= $requestData['report_html'];
$loggedUser= Auth::user();
$reportAvailableSpacesByZonesAcceptorsArray = config('app.reportAvailableSpacesByZonesAcceptorsArray', []);
$site_name = config('app.name', '');
if ( count($reportAvailableSpacesByZonesAcceptorsArray) == 0 ) {
return response()->json(['error_code' => 1, 'message' => 'There are no receiver emails specified !'], HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
}
$to= $reportAvailableSpacesByZonesAcceptorsArray[0];
$subject= 'Available Spaces By Zones report was sent at ' . $site_name;
$additiveVars= [ 'html'=> $report_html ];
unset($reportAvailableSpacesByZonesAcceptorsArray[0]);
$cc= $reportAvailableSpacesByZonesAcceptorsArray;
\Mail::to($to)->send( new SendgridMail( 'emailContainer', $to, $cc, $subject , $additiveVars ) );
return response()->json(['error_code' => 0, 'message' => '', 'user'=> $loggedUser->id], HTTP_RESPONSE_OK);
}
and with Sendgrid service report is sent to users defined in config ok.
Now I need to run this report and send email to recievers in scheduler.
I created a new command :
php artisan make:command reportAvailableSpacesByZones --command=report:available-spaces-by-zones
which has handle method:
public function handle()
{
\Log::info( 'Report run # ' . time() );
}
which is triggered in scheduled time.
But how can I run my report and sent it's content like it is done manually ?
Modified block :
My report is run by (local )url :
http://local-boxbooking2.com/admin/report/available-spaces-by-zones
I remade so that if to run url
http://local-boxbooking2.com/admin/report/available-spaces-by-zones/send-email-on-open
in browser report is opened and checking “send-email-on-open” javascript function is triggered to sent by
email (with Sendgrid service ) content of the page(report actually)
I tried to trigger command by cron tasks :
In app/Console/Commands/reportAvailableSpacesByZones.php :
class reportAvailableSpacesByZones extends Command
{
public function handle()
{
\Log::info( 'Report From inside app/Console/Commands/reportAvailableSpacesByZones.php run # ' . time() );
return redirect()->to('/admin/report/available-spaces-by-zones/send-email-on-open');
}
I see log info , but no reports by email.
Which way is correct ?
Thanks!
In app/Console/Kernal.php add the command to the protected commands array
'App\Console\Commands\reportAvailableSpacesByZones',
in the scheudle method add
$schedule->command('cron:reportAvailableSpacesByZones')->weeklyOn(2, '20:30');
other commands available
https://laravel.com/docs/5.8/scheduling
on the server crontab
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Related
I'm doing a function in laravel, where my user registers a template message:
public function createTemplate(Request $request)
{
if(!($error = $this->isNotValidate($request))){
//Log::error(print_r("validado", true));
$message = Message::create($request->toArray());
//job that runs every day calling my sendMessag
$response = ['message' => $message];
return response($response, 200);
}
return response($error, 422);
}
I want that after registering this mangem, trigger a service that will run every day at the same time, then within this function I will implement my message trigger logic:
public function sendMessage()
{
$messages = Message::where('type', 'like', 'template')->get();
foreach ($messages as $message){
if(/*logic if send message or not*/){
$recive_ids = //get my recive_ids
$users = User::where('user_group', $recive_ids)->get();
Notification::send($users, new MessageNotification($message));
}
}
}
How do I create this job that runs every day calling my sendMessage function?
You can use the Laravel Schedule Feature to run your function or any command.
First, you have to find a suitable method for your need.
After that, you have to update the schedule function which is available in app/Console/Kernel.php
->dailyAt('13:00');
As per your requirement, you need a scheduling method dailyAt().
Second, add the schedule:run command in crontab to run every minute
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
You should refer to this document for more informationSchedule Document
I have a project that uses Ionic and Laravel as a backend. The user uses our app based on monthly or annual subscriptions. So far I have been successful in implementing the initial charge of the subscriptions via peach payment.
So now I want every month end to charge the recurring monthly or annual subscriptions.
The idea I have is as follow:
Run Scheduler to check subscriptions table for all monthly active users where the expiry date is month-end (31/12/2020) or is the current month.
Generate transactions for all those users and save them to the billing table ( this is to get transaction_id to send to a payment gateway).
Run the scheduler using the billing info where created_at is today, send each transaction to payment gateway api for processing.
On Api response get status of each payment request and save/update the db billing table using transaction_id as primaryKey.
Update the subscriptions table (status, new expiry date) after the billing table is update
Any help or direction with this will be appreciated. The code below is the code to use for sending a single charge request.
/**
* Monthly Subscriptions
* #param Request $request
*/
public function chargeMonthlySubscription(Request $request)
{
$curl = curl_init();
$url = "$this->url/registrations/$request->registrationId/payments";
$data = "entityId=$this->entityId" .
"&amount=$request->subscription_amount" .
"¤cy=ZAR" .
"&customer.merchantCustomerId=$request->subscription_no" .
"&customer.givenName=$request->first_name" .
"&customer.surname=$request->last_name" .
"&recurringType=$request->recurring_type" .
"&paymentType=DB";
curl_setopt_array($curl, array(
CURLOPT_URL => "$url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
$this->token,
"Content-Type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
You can make a cron job that will run at the end of the month, first create a command:
php artisan make:command YourCommand
Your command would look like something else:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class YourCommand extends Command
{
//Name that will be used to call command
protected $signature = 'your:command';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
//Here you will handle all the logic. For ex:
$record = App/Example::first();
//Implement condition that will determine if the record will be updated
$record->update();
}
}
After that, inside App/Console/Kernel.php create the schedule for that command:
protected function schedule(Schedule $schedule)
{
//Name that you gave it in the protected $signature = 'your:command';
$schedule->command('your:command')->monthly('23:30');
}
This way the command will be run monthly and you can do anything according to your business logic. You can read more about task scheduling & commands on the official docs.
First I save the file in my public folder, then I want to send an email to the admin with that file attached.
public function upload(Request $request){
if($file = $request->file('pre_qualification')){
$name = $file->getClientOriginalName();
$file->move('submissions', $name);
$form = Form::create([
'pre_qualification'=> $name,
'user_id' => Auth::id()
]);
$today=date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s")." +2 minutes"));
Mail::later($today,new PreQualificationNotification($form));
return redirect()->route('buyer.dashboard');
}
}
Then this is in my Mailable class:
public function __construct($form)
{
$this->form = $form;
$this->to('esp.sousa#gmail.com', $this->form->user->name);
$this->subject('See attached new pre-qualification form submitted');
}
public function build()
{
return $this->view('emails.PreQualification')
->attach(public_path('/submissions/pre-qualification.pdf'));
}
After I submit, the file goes to the public folder, but when I view the page I see an execution time error:
Maximum execution time of 30 seconds exceeded
The idea of using the later function was exactly to avoid that. So, how can I send the email to the admin, attaching the uploaded file?
Try to change max_execution_time=30 in php.ini to some bigger amount.
Or better to use max_execution_time ( int $seconds ) in your script.
You should try this
set_time_limit( int $seconds );
I have been banging my head for last 3 days to set cron for my website. In my cpanel I have mentioned a cron which will run every 5 minutes and command is
wget http://www.example.com/artisan cron:run
In my artisan I have added
Artisan::add(new CronRunCommand);
And CronRunCommand.php is
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class CronRunCommand extends Command {
protected $name = 'cron:run';
protected $description = 'Run the scheduler';
protected $timestamp;
protected $messages = array();
protected $runAt = '03:00';
public function __construct()
{
parent::__construct();
$this->timestamp = time();
}
public function fire()
{
$this->everyFiveMinutes(function()
{
// In the function, you can use anything that you can use everywhere else in Laravel.
$affectedRows = User::where('logged_in', true)->update(array('logged_in' => false)); // Not really useful, but possible
Artisan::call('auth:clear-reminders');
$this->messages[] = $affectedRows . ' users logged out';
});
$this->dailyAt('09:00', function()
{
Mail::send('hello', array(), function($message)
{
$message->to('admin#mydomain.com', 'Cron Job')->subject('I am still running!');
});
});
$this->finish();
}
protected function finish()
{
// Write execution time and messages to the log
$executionTime = round(((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000), 3);
Log::info('Cron: execution time: ' . $executionTime . ' | ' . implode(', ', $this->messages));
}
protected function yearly(callable $callback)
{
if(date('m', $this->timestamp) === '01' && date('d', $this->timestamp) === '01' && date('H:i', $this->timestamp) === $this->runAt) call_user_func($callback);
}
}
And in my email I am getting this message:
404 Not Found
2015-09-06 04:38:02 ERROR 404: Not Found.
--2015-09-06 04:38:02-- ftp://cron/run
=> “run”
Resolving cron... failed: Name or service not known.
wget: unable to resolve host address “cron”
This worked absolutely fine and I have started regular emails
wget http://www.example.com/protected/app/controllers/TestController.php
Hi i am laravel 4 begginer.
i try to use Artadek/OAuth-4-laravel package
Everything went well untill using the example what i did:
Route:
Route::get('lfb', array(
'as' => 'lfb',
'uses' => 'HomeController#signInWithFacebook'
));
Controller:
class HomeController extends BaseController {
public function signInWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
And blade :
#extends('layout.main')
#section('content')
Sign in with Facebook
#stop
Last error log from laravel.log:
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
open: F:\wamp\www\IbidsLR\bootstrap\compiled.php
{
$routes = $this->get($request->getMethod());
$route = $this->check($routes, $request);
if (!is_null($route)) {
return $route->bind($request);
}
$this->checkForAlternateVerbs($request);
throw new NotFoundHttpException();
}
protected function checkForAlternateVerbs($request)
And i get when press on the button "Whoops,somthing went wrong." and it redirect me to lfb page which i dont have any page called that name i just want to use fb login..
What wrong here?
Goes to your laravel folder, then open app/config/app.php and make sure 'debug' => 'true' and it will help you showing what kinds of error you are having now.
It is working fine with your routes and also signInWithFacebook() function. Make sure that you already created a config file for Artadek/OAuth-4-laravel package, and it will be in app/config/packages.
It is showing lfb page because that is your route -- your function will be working with it.
Please make sure debug is on and check your error again. It is hard to explain with just that 'Whoops, something went wrong.'