Limit Queued Job in Laravel - laravel

I have an email service that allows me to send only 60 emails per hour (1/minute).
So that is why i m trying to write an application that respect the service provider's restrictions,
I m dispatching emails to bulk users at once via queue jobs,Please take a look at the code
public function sendEmails(CreateEmailRequest $request)
{
$data = [];
$users = User::find($request->to);
$subject = $request->subject;
$body = $this->fileUpload($request->body);
foreach ($users as $user) {
$vars = array(
"{{name}}" => $user->name,
"{{email}}" => $user->email,
);
$body = strtr($body, $vars);
$data['body'] = $body;
$data['user'] = $user;
$data['subject'] = $subject;
dispatch(new SendEmailJob($data))->onQueue('mail');
}
Flash::success('Email sent successfully.');
return redirect(route('emails.index'));
}
here is SendEmailJob Class code
public function handle()
{
$data = $this->data;
$body = $data['body'];
$user = $data['user'];
$subject = $data['subject'];
// list($body, $user, $subject) = $this->data;
Mail::send('mail.email', ['body' => $body], function ($m) use ($user, $subject) {
$m->to($user->email)->subject($subject);
});
}
public function middleware()
{
return Limit::perMinute(1);
}
when I run php artisan queue:work it process all jobs at once..
can you please tell me how can I achieve this?
I can not use spatie/laravel-rate-limited-job-middleware because my server does not support Redis.
Can you please tell me i m doing wrong ?

You can use Job Middleware with a rate limiting
in the boot method of your AppServiceProvider
RateLimiter::for('emails', function($job) {
return Limit::perMinute(1);
});
and add middleware to the job:
use Illuminate\Queue\Middleware\RateLimited;
public function middleware()
{
return [new RateLimited('emails')];
}

Related

send an email in Laravel on a create function

send an email in Laravel on a create function but not able to do
this is my store function
public function store()
{
$input = $request->all();
$user = \AUTH::guard()->user();
$input['created_by'] = $user->id;
\Log::info('$input'.json_encode([$input]));
$bulkLabSample = $this->bulkLabSampleRepository->create($input);
Flash::success(__('messages.saved', ['model' => __('models/bulkLabSamples.singular')]));
return redirect(route('bulkLabSamples.index'));
}
// use this
use Illuminate\Support\Facades\Mail;
// send mail via mail
Mail::send('your-view-blade', ['extraInfo' => $extraInfo], function ($message) {
$message->to('email#email.com');
$message->subject('your subject here');
});
By extraInfo you can pass values to the mail template as you want.
// for your code
public function store()
{
$input = $request->all();
$user = \AUTH::guard()->user();
$input['created_by'] = $user->id;
\Log::info('$input'.json_encode([$input]));
$bulkLabSample = $this->bulkLabSampleRepository->create($input);
Mail::send('your-view-blade', ['extraInfo' => $extraInfo], function ($message) {
$message->to('email#email.com');
$message->subject('your subject here');
});
Flash::success(__('messages.saved', ['model' => __('models/bulkLabSamples.singular')]));
return redirect(route('bulkLabSamples.index'));
}

Auth user not added

This code is work fine but when i use auth::id than show error like this in api Message unauthenticated
API
Route::post('/friend', 'FriendController#index')->middleware('auth');
Working code
public function index(Request $request) {
$sender = Friend::where('sender_id', $request->sender_id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>$request->sender_id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
}
return response()->json($response);
}
Not working code, error message unauthenticated
public function index(Request $request) {
//$user = Auth::user()->id;
$sender = Friend::where('sender_id', $request->Auth::user()->id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>$request->Auth::user()->id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
}
return response()->json($response);
}
How can i add sender_id is authenticated user id?
auth()->id()
or
$request->user()->id
This will give you id of loggedin User
Also check your middleware it should be
->middleware('auth:api')
You should not use $request->Auth::user()->id to get the id of authenticated user ., Instead use this directly to get id.
Auth::user()->id
Code :
public function index(Request $request) {
//$user = Auth::user()->id;
$sender = Friend::where('sender_id', Auth::user()->id)->where('receiver_id',$request->receiver_id)->first();
if(empty($sender)){
Friend::create(['sender_id'=>Auth::user()->id,'receiver_id'=>$request->receiver_id, 'approved'=>'pending']);
$response = ['message'=>'Friend Request has been sent','status'=>200];
}else{
$response = ['message'=>'Request has been sent already','status'=>200];
}
return response()->json($response);
}
try changing
$request->Auth::user()->id
to
Auth::user()->id

How to send email via table data as email laravel

I'm trying to send an email via Laravel that has table data attached to it and I'm having some trouble. Here is a snippet of the code I'm running:
public function pdfview(Request $request)
{
$items = DB::table("motor_vehicles")->get();
view()->share('vehicles', $items);
if ($request->has('download')) {
$pdf = PDF::loadView('pdfview');
$this->sendEmail();
return $pdf->download('pdfview.pdf');
}
return view('pdfview');
}
public function sendEmail()
{
Mail::send(['text' => 'mail'], $info, function ($message) {
$pdf = PDF::loadView('pdfview');
$message->to('inchiriseri#gmail.com', 'Itai Chiriseri')->subject('Sent Table Data');
$message->from('inchiriseri#gmail.com', 'Itai Chiriseri');
$message->attachData($pdf->output(), 'pdfview.pdf');
});
}

How to compare otp number without reload page which send in sms?

I want to compare otp numbers, which i type in textbox and sms otp sent to the number through api calling controller in laravel.
i use laravel5.6 and php 7.2.3
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
i want to compare textbox otp number and sms otp number sent through api calling and redirect with another controller in laravel5.6
The thing is you must store your otp in database or in session variable.
(Documentation: https://laravel.com/docs/5.8/eloquent)
You can store otp in database like
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
User::where('phone_number',$req->txtnumber)->update(['otp'=>$otp]);
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it using eloquent in Laravel using
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
$otp = User::where('phone_number', $phone_number)->first()->otp;
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
after entering the correct otp clear that in database.
Or you can use session.you can use session in two ways
1.php default session
2.Laravel Session
let us see php default session
(documentation:https://www.php.net/manual/en/book.session.php)
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
session_start();
$_SESSION['otp'] = $otp
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it by
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
session_start();
$otp = $_SESSION['otp']
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
let us use laravel session
(documentation: https://laravel.com/docs/5.2/session)
//important
use Illuminate\Support\Facades\Session;
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
Session::put('otp',$otp)
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it by
//important
use Illuminate\Support\Facades\Session;
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
$otp = Session::get('otp') //best way to use is flash. see the full documentation
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}

Creating edit function in the same controller laravel

So I have a create function in my controller as shown below and my routes is as such, my question is is there a way for me to put a condition to different create and edit in the same function as both have quite similar coding. Can someone enlighten me pls?
class ManageAccountsController extends Controller
{
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function update()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the user table
'password' => 'required|min:8|alpha_num',
'password_confirm' => 'required|same:password', // required and has to match the password field
'mobile' => 'required',
'role_id' => 'required'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back to the form with the errors from the validator
$input = Input::except('password', 'password_confirm');
$input['autoOpenModal'] = 'true'; //Add the auto open indicator flag as an input.
return redirect()
->back()
->withInput($input)
->withErrors($validator);
} else {
// validation successful ---------------------------
// user has passed all tests!
// let user enter the database
// create the data for our user
$user = new User;
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->mobile = Input::get('mobile');
$user->role_id = Input::get('role_id');
// save our user
$user->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
}
}
routes.php
Route::get('manage_accounts', 'ManageAccountsController#index');
Route::post('manage_accounts', 'ManageAccountsController#update');
UPDATE OR CREATE
Try the updateOrCreate() in Eloquent to create or update a record matching the attributes.
Read API docs udateOrCreate()
Your code will be like:
Model::updateOrCreate( ['id' => $id], ['firstField' => 'value', 'secondField' => 'value'] );
Note: first parameter is the match to be found and second the data's to be saved.
Hope this is helpful.
Why don't you try moving some of this code out of your controller. If you were to use Repositories, then you would be able to encapsulate some of your logic in order to use it for both functions.
Also you can handle all this validation without writing all the extra code into your controller - see http://laravel.com/docs/5.0/validation#form-request-validation.
This may all seem a bit overkill at first, but once you get the hang of it, your code will be much more manageable and extendable.
(for more on these I would thoroughly recommend Jeffery Way's Laracasts https://laracasts.com/ - this helped me a lot when I was learning Laravel)
// routes.php
// http://laravel.com/docs/5.0/controllers#restful-resource-controllers
Route::resource('manage_accounts', 'ManageAccountsController');
// ManageAccountsController.php
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index() {
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function store(StoreUserRequest $request)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request)
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
public function update(StoreUserRequest $request, $id)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request, $id)
Session::flash('flash_message', 'User successfully updated!');
return redirect()->back();
}
}
// UserRepository.php
class UserRepository {
public function upsert($data, $id = null)
{
// You will also need something like this
if(isset($data['id']))
{
$user = $this->user->find($data['id']);
}
else {
$user = new User;
}
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}
}
Please use the code here as a guide (I have written this in a hurry and it will certainly contain errors). Have a quick read up on repositories and I think it should all make sense.
The basic premise here is to separate out code that you want to re-use rather than squashing it all into the same function.
Hope this helps!

Resources