Type error: Too few arguments to function Illuminate\Mail\Mailer::__construct(), 0 passed - Laravel 5.5 - laravel

I keep getting while trying to use the mailer
FatalThrowableError in Mailer.php line 93:
Type error: Too few arguments to function Illuminate\Mail\Mailer::__construct(), 0 passed in /var/www/app/app/Services/SendOtpMail.php on line 42 and at least 2 expected
in Mailer.php line 93
at Mailer->__construct() in SendOtpMail.php line 42
at SendOtpMail->send('test#company.com', array('from' => 'no-reply#company.com', 'from_name' => 'Some Company', 'subject' => 'Login Verification', 'data' => array('token' => '3486', 'user' => object(User)), 'view' => 'emails.password')) in GetOtpForLoginService.php line 59
at GetOtpForLoginService->sendEmail('3486', object(User))
Send mail function
public function sendEmail($otp, $user)
{
$user = User::where('email', $user->email)->firstOrFail();
(new SendOtpMail())->send($user->email, [
'from' => env('MAIL_DEAFULT_SENDER'),
'from_name' => env('MAIL_DEAFULT_SENDER_ALIAS'),
'subject' => 'Login Verification',
'data' => [
'token' => $otp,
'user' => $user
],
'view' => 'emails.password'
]);
return true;
}
SendOtpMail.php
<?php
namespace App\Services;
use Illuminate\Mail\Mailer;
class SendOtpMail
{
public function send($to, array $options = array())
{
$callback = function($message) use ($options, $to) {
$message->from($options['from'], isset($options['from_name']) ? $options['from_name'] : null);
$message->to($to, isset($options['to_name']) ? $options['to_name'] : null);
if(isset($options['subject'])) $message->subject($options['subject']);
if(isset($options['priority'])) $message->priority($options['priority']);
if(isset($options['priority'])) $message->priority($options['priority']);
if(isset($options['files'])) {
if (is_array($options['files'])) {
foreach ($options['files'] as $file) {
$message->attach($options[$file]);
}
} else {
$message->attach($options['files']);
}
}
if(isset($options['cc'])) $message->subject($options['cc'], isset($options['cc_name']) ? $options['cc_name'] : null);
if(isset($options['bcc'])) $message->subject($options['bcc'], isset($options['bcc_name']) ? $options['bcc_name'] : null);
};
if(isset($options['view'])) {
$data = isset($options['data']) ? $options['data'] : array();
(new Mailer())->send($options['view'], $data, $callback);
} else {
(new Mailer())->raw($options['message'], $callback);
}
}
}

You are seeing that error because you are instantiating an Illuminate\Mail\Mailer object without specifying its required parameters in the constructor:
// from Laravel source code
public function __construct(string $name, Factory $views, TransportInterface $transport, Dispatcher $events = null)
{
$this->name = $name;
$this->views = $views;
$this->events = $events;
$this->transport = $transport;
}
I suggest you don't send emails this ways. Pls check the docs and follow the instructions.

Related

Laravel ErrorException Undefined variable in my public function

I ran into the error:
ErrorException Undefined variable: pesan
I have gone through similar problems solved here but none of the solutions have worked for me.
The error is thrown from my RegisterController at bottom of the line. At the pesan
I use laravel 8
Here is my controller code:
` public function simpan_rm(Request $request)
{
$this->validate($request, [
'idpasien' => 'required|numeric|digits_between:1,4',
'keluhan_utama' => 'required|max:40',
'anamnesis' => 'required|max:1000',
'px_fisik' => 'max:1000',
'diagnosis' => 'max:40',
'dokter' => 'required',
]);
// Decoding array input pemeriksaan lab
if (isset($request->lab))
{
if (has_dupes(array_column($request->lab,'id'))){
$errors = new MessageBag(['lab'=>['Lab yang sama tidak boleh dimasukan berulang']]);
return back()->withErrors($errors);
}
$this->validate($request, [
'lab.*.hasil' => 'required|numeric|digits_between:1,4',
]);
$lab_id = decode('lab','id',$request->lab);
$lab_hasil = decode('lab','hasil',$request->lab);
}
else {
$lab_id ="";
$lab_hasil ="";
}
// Decoding array input resep
if (isset($request->resep))
{
if (has_dupes(array_column($request->resep,'id'))){
$errors = new MessageBag(['resep'=>['resep yang sama tidak boleh dimasukan berulang']]);
return back()->withErrors($errors);
}
$this->validate($request, [
'resep.*.jumlah' => 'required|numeric|digits_between:1,3',
'resep.*.aturan' => 'required',
]);
$resep_id = decode('resep','id',$request->resep);
$resep_jumlah = decode('resep','jumlah',$request->resep);
$resep_dosis = decode('resep','aturan',$request->resep);
}
else {
$resep_id = "";
$resep_jumlah = "";
$resep_dosis = "";
}
$newresep = array();
$oldresep=array();
if (is_array($request) || is_object($newresep))
{
foreach ($request->resep as $resep){
$newresep[$resep['id']] = $resep['jumlah'];
}
}
if (empty($oldresep)) {
$resultanresep = resultan_resep($oldresep,$newresep);
}
else {$resultanresep=$newresep;}
$errors = validasi_stok($resultanresep);
if ($errors !== NULL) {
return back()->withErrors($errors);
}
foreach ($resultanresep as $key => $value) {
$perintah=kurangi_stok($key,$value);
if ($perintah === false) { $habis = array_push($habis,$key); }
}
DB::table('rm')->insert([
'idpasien' => $request->idpasien,
'ku' => $request->keluhan_utama,
'anamnesis' => $request->anamnesis,
'pxfisik' => $request->px_fisik,
'lab' => $lab_id,
'hasil' => $lab_hasil,
'diagnosis' => $request->diagnosis,
'resep' => $resep_id,
'jumlah' => $resep_jumlah,
'aturan' => $resep_dosis,
'dokter' => $request->dokter,
'created_time' => Carbon::now(),
'updated_time' => Carbon::now(),
]);
$ids= DB::table('rm')->latest('created_time')->first();
switch($request->simpan) {
case 'simpan_edit':
$buka=route('rm.edit',$ids->id);
$pesan='Data Rekam Medis berhasil disimpan!';
break;
case 'simpan_baru':
$buka=route('rm.tambah.id',$request->idpasien);;
$pesan='Data Rekam Medis berhasil disimpan!';
break;
}
return redirect('buka')->with('pesan',$pesan);
}`
Unfortunately i've modified return redirect('buka')->with('pesan',$pesan); but didn't work for me.
Please help
$pesan is defined in 2 cases of your switch statement.
So what happens when $request->simpan is neither equal to simpan_edit or simpan_baru ?
In this case (wich is not handled in your code), $pesan will be undefined and an error will throw.
A good practice using switch statements is to add a default: case wich will match any other values that you didn't explicitely set a case: for.
Example :
switch($request->simpan) {
case 'simpan_edit':
$buka=route('rm.edit',$ids->id);
$pesan='Data Rekam Medis berhasil disimpan!';
break;
case 'simpan_baru':
$buka=route('rm.tambah.id',$request->idpasien);;
$pesan='Data Rekam Medis berhasil disimpan!';
break;
default:
// you may set a default value for `$pesan` here
$pesan=null;
}
it seems that the error is related to the $pesan variable, according to the code you've provided, $pesan is not defined anywhere in the controller, which is why you're receiving the Error Exception Undefined variable : pesan error
for resolve this issue, you should either define the $pesan variable or remove any reference to it in the code
if $pesan is meant to store some message, it should be defined and assigned a value before being used

How to define variable in controller in laravel

I have a URL used in blade template as:
href="{{ route('download', ['year' => $year, 'month' => $month, 'file' => $file_path]) }}"
when I am running my code then it is giving me an error as:
Undefined variable: year (View: C:\wamp64\www\Blog\employee-portal\resources\views\finance\invoice\edit.blade.php)
How can i define this $year variable in my controller?
In my controller the function is written as:
public function download($year, $month, $file, $inline = true)
{
$headers = [
'content-type' => 'application/pdf',
];
$file_path = FileHelper::getFilePath($year, $month, $file);
if (!$file_path) {
return false;
}
if ($inline) {
return Response::make(Storage::get($file_path), 200, $headers);
}
return Storage::download($file_path);
}
}
Edit function is written as:
public function edit(Invoice $invoice)
{
$projectStageBillings = $invoice->projectStageBillings;
$projectStageBilling = $projectStageBillings->first();
$client = $projectStageBilling->projectStage->project->client;
$client->load('projects', 'projects.stages', 'projects.stages.billings');
$billings = [];
foreach ($projectStageBillings as $key => $billing) {
$billing->load('projectStage', 'projectStage.project');
$billings[] = $billing;
}
return view('finance.invoice.edit')->with([
'invoice' => $invoice,
'clients' => Client::select('id', 'name')->get(),
'invoice_client' => $client,
'invoice_billings' => $billings,
]);
}
This error states that the view finance\invoice\edit.blade.php is missing the variable $year. And it is true, take a look at the return of your edit function:
return view('finance.invoice.edit')->with([
'invoice' => $invoice,
'clients' => Client::select('id', 'name')->get(),
'invoice_client' => $client,
'invoice_billings' => $billings,
]);
You are not sending any $year variable to the view here (the variables sent to the view are invoice,clients,invoice_client and invoice_billings.
To solve your problem, just send a $year variable to the view and you'll be ok :)

Extend Laravel package

I've searched around and couldn't find a definitive answer for this...
I have a package DevDojo Chatter and would like to extend it using my application. I understand I'd have to override the functions so that a composer update doesn't overwrite my changes.
How do I go about doing this?
UPDATE
public function store(Request $request)
{
$request->request->add(['body_content' => strip_tags($request->body)]);
$validator = Validator::make($request->all(), [
'title' => 'required|min:5|max:255',
'body_content' => 'required|min:10',
'chatter_category_id' => 'required',
]);
Event::fire(new ChatterBeforeNewDiscussion($request, $validator));
if (function_exists('chatter_before_new_discussion')) {
chatter_before_new_discussion($request, $validator);
}
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$user_id = Auth::user()->id;
if (config('chatter.security.limit_time_between_posts')) {
if ($this->notEnoughTimeBetweenDiscussion()) {
$minute_copy = (config('chatter.security.time_between_posts') == 1) ? ' minute' : ' minutes';
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'In order to prevent spam, please allow at least '.config('chatter.security.time_between_posts').$minute_copy.' in between submitting content.',
];
return redirect('/'.config('chatter.routes.home'))->with($chatter_alert)->withInput();
}
}
// *** Let's gaurantee that we always have a generic slug *** //
$slug = str_slug($request->title, '-');
$discussion_exists = Models::discussion()->where('slug', '=', $slug)->first();
$incrementer = 1;
$new_slug = $slug;
while (isset($discussion_exists->id)) {
$new_slug = $slug.'-'.$incrementer;
$discussion_exists = Models::discussion()->where('slug', '=', $new_slug)->first();
$incrementer += 1;
}
if ($slug != $new_slug) {
$slug = $new_slug;
}
$new_discussion = [
'title' => $request->title,
'chatter_category_id' => $request->chatter_category_id,
'user_id' => $user_id,
'slug' => $slug,
'color' => $request->color,
];
$category = Models::category()->find($request->chatter_category_id);
if (!isset($category->slug)) {
$category = Models::category()->first();
}
$discussion = Models::discussion()->create($new_discussion);
$new_post = [
'chatter_discussion_id' => $discussion->id,
'user_id' => $user_id,
'body' => $request->body,
];
if (config('chatter.editor') == 'simplemde'):
$new_post['markdown'] = 1;
endif;
// add the user to automatically be notified when new posts are submitted
$discussion->users()->attach($user_id);
$post = Models::post()->create($new_post);
if ($post->id) {
Event::fire(new ChatterAfterNewDiscussion($request));
if (function_exists('chatter_after_new_discussion')) {
chatter_after_new_discussion($request);
}
if($discussion->status === 1) {
$chatter_alert = [
'chatter_alert_type' => 'success',
'chatter_alert' => 'Successfully created a new '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
} else {
$chatter_alert = [
'chatter_alert_type' => 'info',
'chatter_alert' => 'You post has been submitted for approval.',
];
return redirect()->back()->with($chatter_alert);
}
} else {
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'Whoops :( There seems to be a problem creating your '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
}
}
There's a store function within the vendor package that i'd like to modify/override. I want to be able to modify some of the function or perhaps part of it if needed. Please someone point me in the right direction.
If you mean modify class implementation in your application you can change the way class is resolved:
app()->bind(PackageClass:class, YourCustomClass::class);
and now you can create this custom class like so:
class YourCustomClass extends PackageClass
{
public function packageClassYouWantToChange()
{
// here you can modify behavior
}
}
I would advise you to read more about binding.
Of course a lot depends on how class is created, if it is created using new operator you might need to change multiple classes but if it's injected it should be enough to change this single class.

Call to undefined method Product_model::product()

public function save_edit() {
parent::__save_edit();
$this->db = $this->load->database('default', true);
$this->load->model('product_model','',TRUE);
$id = $this->input->post('item_id');
$array_item = array(
'item_name' => $this->input->post('item_name'),
'note' => $this->input->post('item_note'),
'stock' => $this->input->post('item_stock'),
'price' => $this->input->post('item_price'),
'unit' => $this->input->post('item_unit')
);
$this->load->model('product_model');
$this->product_model->update($id,$array_item);
redirect('index.php/product');
}
public function edit(){
$this->db = $this->load->database('default', true);
$this->load->model('product_model');
**$data['product'] = $this->product_model->product($this->uri->segment(3))->row_array();**
$this->load->view('index.php/product_edit',$data);
}
error at line
$data['product'] = $this->product_model->product($this->uri->segment(3))->row_array();
your get this error because. your model i.e "product_model" does not contain any product function.
Hence you get "Call to undefined method Product_model::product()" error

CakePHP login when trying to acces controller

im having troubles with a web app that a teacher ask me to modify, the problem its that i dont know about cakePHP and i have been having troubles.After reading a lot, i think i have grasped the basics of the framework. My problem now its that i have a link in a view so i call a function in the controller to retrive data from the model, the problem its that each time i try to acces the function , the app makes me log in, and the idea its that it shouldnt.
I dont know exactly how the session handling on cakePhp works so, im requesting some help.
the code for the controller its this:
<?php
class RwController extends AppController {
var $name = 'Rw';
// var $paginate = array(
// 'Tip' => array(
// 'limit' => 1,
// 'order' => array(
// 'tip.created' => 'desc'
// ),
// ),
// 'Evento' => array(
// 'limit' => 1,
// 'order' => array(
// 'evento.fecha' => 'desc'
// ),
// )
// );
function map() {
$this->helpers[]='GoogleMapV3';
}
function pageForPagination($model) {
$page = 1;
// $chars = preg_split('/model:/', $this->params['url']['url'], -1, PREG_SPLIT_OFFSET_CAPTURE);
// #print_r($chars);
// if(sizeof($chars) > 1 && sizeof($chars) < 3) {
// #echo "Belongs to ".$model.": \n";
// #echo var_dump($chars);
// }
// $params = Dispatcher::parseParams(Dispatcher::uri());
// echo "<p>".var_dump($params)."</p><br />";
#echo $this->params['named']['model'].$model;
#echo $this->params['named']['page'];
$sameModel = isset($this->params['named']['model']) && $this->params['named']['model'] == $model;
$pageInUrl = isset($this->params['named']['page']);
if ($sameModel && $pageInUrl) {
$page = $this->params['named']['page'];
} else {
#echo var_dump($this->passedArgs);
}
$this->passedArgs['page'] = $page;
return $page;
}
function index() {
$this->log('indexeando esta chingadera','debug');
$this->loadModel('User');
$this->loadModel('Evento');
$this->loadModel('Tip');
$dataEvento = $this->Evento->find('all');
$dataTip = $this->Tip->find('all');
$page = $this->pageForPagination('Evento');
$this->paginate['Evento'] = array(
'contain' => false,
'order' => array('Evento.fecha' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataEvento = $this->paginate('Evento');
$page = $this->pageForPagination('Tip');
$this->paginate['Tip'] = array(
'contain' => false,
'order' => array('Tip.created' => 'desc'),
'limit' => 1,
'page' => $page
);
$dataTip = $this->paginate('Tip');
$this->set('users', $this->User->find('all'));
$this->set('eventos', $dataEvento);
$this->set('tips', $dataTip);
$this->set('rw');
if(isset($this->params['named']['model'])) {
if (strcmp($this->params['named']['model'], 'Evento') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_evento_paginate');
return;
}
} elseif (strcmp($this->params['named']['model'], 'Tip') == 0) {
if($this->RequestHandler->isAjax()) {
$this->render('/elements/ajax_rw_tip_paginate');
return;
}
}
}
}
function about($id = null) {
$this->Rw->recursive = 0;
$this->set('rw', $this->paginate());
}
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow(array('index', 'about'));
}
function getCentros($id){
$this->loadModel('Centro');
$this->log('getcentros','debug');
if( sizeof($id) > 1){
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'
OR material_id='".$id[1]."'"));
}elseif( sizeof($id) >0) {
if($id == 0){
$this->set('centros', $this->Centro->find('all'));
}else{
$this->set('centros', $this->Centro->query("SELECT centros.id, name, latitud ,longitud
FROM `centros`,`centrosmateriales`
WHERE centros.id = centro_id
AND material_id ='".$id[0]."'"));
}
}
$this->redirect(array('action' => 'index'));
}
}
?>
Edit:
The function im calling is getCentros().
this is what i have in app_controller.
<?php
class AppController extends Controller {
var $components = array('Session', 'Auth', 'RequestHandler');
var $helpers = array('Html', 'Form', 'Time', 'Session', 'Js', 'Paginator', 'GoogleMapV3');
function beforeFilter() {
$this->Auth->userModel = 'User';
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Auth->loginAction = array('admin' => false, 'controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
}
}
?>
try this
$this->Auth->allow(array('*'));
it allows you to access all functions inside the controller.
But before that make sure that you have access on the controller with out errors because your controller name is like this
class RwController extends AppController {
}
may be it want like this
class RwsController extends AppController {
}
Don't know which function you are trying to call but if cake tries to log you in and you don'want this add the function to:
$this->Auth->allow(array('index', 'about'));
in your beforefilter

Resources