pass var from controller to mail class laravel - php

I am trying to send a mail with a attachment. Its based on a var from my controller. But I don't know how to pass the content of the variable from my controller to my mail class. My mail view has no problem with using the vars. I need the var in the build method to pick the right file from my directory I generated in my controller.
This returns the following
Missing argument 1 for App\Mail\Aanvraag::build()
Mail class
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\App;
use App\Http\Controllers\aanvragenController;
class Aanvraag extends Mailable
{
use Queueable, SerializesModels;
public $aanvraag;
public function __construct($aanvraag)
{
$this->aanvraag = $aanvraag;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mails.aanvraag')->attach(url('/exports/'. $aanvraag->naam .'sheet.xls'));
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Aanvragen;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use App\Mail\Aanvraag;
class aanvragenController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index() {
if (Auth::id() == 1) {
$aanvragen = Aanvragen::all();
} else {
$userid = Auth::id();
$aanvragen = Aanvragen::where('user_id', $userid)
->orderBy('id')
->take(10)
->get();
}
return view('aanvragen.index', compact('aanvragen'));
}
public function create() {
return view('aanvragen.create');
}
public function store() {
/* $this->validate(request(), [
'studentnummer' => 'unique:aanvragen'
]);*/
$aanvraag = new Aanvragen;
$aanvraag->naam = request('naam');
$aanvraag->studentnummer = request('studentnummer');
$aanvraag->email = request('email');
$aanvraag->telefoonnummer = request('telefoonnummer');
$aanvraag->stagebedrijf = request('stagebedrijf');
$aanvraag->contactpersoon = request('contactpersoon');
$aanvraag->emailContact = request('emailContact');
$aanvraag->telefoonContact = request('telefoonContact');
$aanvraag->begindatum = request('begindatum');
$aanvraag->einddatum = request('einddatum');
$aanvraag->user_id = Auth::id();
$aanvraag->save();
$data = array (
array('Naam', 'Studentnummer', 'Email', 'Telefoonnummer', 'Stagebedrijf', 'Contactpersoon', 'Email contactpersoon'
, 'Telefoon contactpersoon', 'begindatum', 'einddatum'),
array($aanvraag->naam, $aanvraag->studentnummer, $aanvraag->email, $aanvraag->telefoonnummer, $aanvraag->stagebedrijf,
$aanvraag->contactpersoon, $aanvraag->emailContact, $aanvraag->telefoonContact, $aanvraag->begindatum, $aanvraag->einddatum
)
);
$attachment = $aanvraag->naam;
\Excel::create($aanvraag->naam.'sheet', function ($excel) use ($data) {
$excel->sheet('Sheet1', function ($sheet) use ($data) {
$sheet->fromArray($data);
});
})->save();
\Mail::to('johndoe#info.com')->send(new Aanvraag($aanvraag));
return redirect('/');
}
}

Related

Project "Address in mailbox given [] does not comply with RFC 2822, 3.6.2." gives a fault

I have a Laravel backend project. This project is currently running in Laravel 8. But sometimes it gives Address in mailbox given [] does not comply with RFC 2822, 3.6.2. error. But as I said, it only gives this error sometimes because when I follow on sentry.io, I only see it two or three times a week. When I look at sentry.io, it shows the error in
App\Http\Controllers\Crons\EmailCronJobController::listenersNothingListenedFor3Days here.
Here is the block:
private function listenersNothingListenedFor3Days(){
$users = User::where([
['role_id','=', 4],
['created_at', '>=', Carbon::now()->subDay(7)->toDateTimeString()],
['created_at', '<', Carbon::now()->subDay(3)->toDateTimeString()]
])->get();
$users = $users->filter(function ($user){
return $user->getFirstListenedContent()==null;
});
/*
foreach ($users as $user){
$email_array = explode('#',$user->email);
$email = $email_array[0].'#etrexio.com';
$user->update(['email'=>$email]);
}*/
foreach ($users as $user){
if($user->getCustomField('nothing_listened_3_days_email_send_date')==null){
Mail::to($user)->send(new NothingListenedFor3Days($user));
$user->setCustomField('nothing_listened_3_days_email_send_date',date('Y-m-d H:i:s'));
}
}
}
EmailCronJobController.php
<?php
namespace App\Http\Controllers\Crons;
use App\Http\Controllers\Controller;
use App\Mail\Listener\FirstContentListen;
use App\Mail\Listener\NothingListenedFor3Days;
use App\RawListeningData;
use App\User;
use App\UserPayment;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class EmailCronJobController extends Controller
{
public function __invoke()
{
$this->listeners();
}
private function listeners(){
$this->listenersFirstContentListen();
$this->listenersNothingListenedFor3Days();
}
private function listenersNothingListenedFor3Days(){
$users = User::where([
['role_id','=', 4],
['created_at', '>=', Carbon::now()->subDay(7)->toDateTimeString()],
['created_at', '<', Carbon::now()->subDay(3)->toDateTimeString()]
])->get();
$users = $users->filter(function ($user){
return $user->getFirstListenedContent()==null;
});
/*
foreach ($users as $user){
$email_array = explode('#',$user->email);
$email = $email_array[0].'#etrexio.com';
$user->update(['email'=>$email]);
}*/
foreach ($users as $user){
if($user->getCustomField('nothing_listened_3_days_email_send_date')==null){
Mail::to($user)->send(new NothingListenedFor3Days($user));
$user->setCustomField('nothing_listened_3_days_email_send_date',date('Y-m-d H:i:s'));
}
}
}
private function testEmail(){
$active_user_payments = UserPayment::select('user_id')->where('exprire_date', '>=', Carbon::now()->toDateTimeString())->get();
$active_users_ids = $active_user_payments->map(function ($payments){
return $payments->user_id;
});
$users = User::whereIn('id',$active_users_ids)->get();
dd($users);
}
private function listenersFirstContentListen(){
$last_24_h_listening = RawListeningData::select('user_id')->where('created_at', '>=', Carbon::now()->subDay()->toDateTimeString())->get();
$last_24_h_listening_users = $last_24_h_listening->map(function ($listening){
return $listening->user_id;
})->unique();
$before_24_h_listening = RawListeningData::select('user_id')->whereIn('user_id',$last_24_h_listening_users)->where('created_at', '<', Carbon::now()->subDay()->toDateTimeString())->get();
$before_24_h_listening_users = $before_24_h_listening->map(function ($listening){
return $listening->user_id;
})->unique();
$result = collect($last_24_h_listening_users)->diff(collect($before_24_h_listening_users));
$users = User::whereIn('id',$result)->get();
foreach ($users as $user){
if($user->getCustomField('first_content_listen_email_send_date')==null){
$content = $user->getFirstListenedContent();
if($content!=null){
Mail::to($user)->send(new FirstContentListen($user,$content));
$user->setCustomField('first_content_listen_email_send_date',date('Y-m-d H:i:s'));
}
}
}
}
}
NothingListenedFor3Days.php
namespace App\Mail\Listener;
use App\Course;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class NothingListenedFor3Days extends Mailable
{
use Queueable, SerializesModels;
public $listener;
public $random_contents;
public $fromEmail = 'listener#omnicourse.io';
public $fromName = 'Omnicourse';
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $listener)
{
$this->listener = $listener;
$this->random_contents = Course::all()->random(10);
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from($this->fromEmail,$this->fromName)
->view('email.listener.nothing_listened_for_3_days')
->text('email.listener.nothing_listened_for_3_days_plain')
->subject("Let's move ahead together");
}
}
What could be the solution to this, I searched a lot, but I couldn't find anything clear.

Call to undefined method Illuminate\Database\Eloquent\Builder::save()

So, what i`m trying to do here is to save an image to an specific user that is logged in. and it gives me this error
<?php
namespace App\Http\Controllers\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Models\ProfileEmployee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class ImageUploadController extends Controller
{
public function index()
{
$profilasdeimage = ProfilasdeEmployee::where('uid', Auth::user()->id)->first();
return vieasdw('editareemasdployee', compact('profileiasdmage'));
}
public function store(Requasdest $request)
{
$emplasdoyee = ProfileEasdmployee::where('uiasdd', Autasdh::user()->id);
if ($request->hasfile('imasdage')){
$file = $request->file('image');
$exteasdnsion = $file->getClientOriginalExtension();
$fileasdname = md5(time()).'.'.$extension;
$fiasdle->move('public/imaginasdeprofil',$filename);
$empasdloyee->imagasde=$filename;
} else {
return $request;
$emplasdoyee->imasdage='';
}
$emplasdoyee->save(); --->> this is the problem
return view('imageuplasdoad')->with('profasdileimage',$emplasdoyee);
}
}
i want to use this database table to fill the 'image' using the id provided from table users as uid in this table
protected $filasdlable = [
'iasdd', 'uiasdd', 'fasdirst_nasdame', 'lasdast_nasdame','phasdone', 'casdv', 'imasdage', 'addasdress', 'ciasdty',
];
Add first() to your query or use find:
$employee = ProfileEmployee::where('uid', Auth::user()->id)->first();

How can you include column headers when exporting Eloquent to Excel in Laravel?

I am trying to allow users to download Excel, using Laravel Excel files with product information. My current web route looks like this:
Route::get('/excel/release', 'ExcelController#create')->name('Create Excel');
My current Export looks like this:
class ProductExport implements FromQuery
{
use Exportable;
public function __construct(int $id)
{
$this->id = $id;
}
public function query()
{
return ProductList::query()->where('id', $this->id);
}
}
My current controller looks like this:
public function create(Request $request) {
# Only alowed tables
$alias = [
'product_list' => ProductExport::class
];
# Ensure request has properties
if(!$request->has('alias') || !$request->has('id'))
return Redirect::back()->withErrors(['Please fill in the required fields.'])->withInput();
# Ensure they can use this
if(!in_array($request->alias, array_keys($alias)))
return Redirect::back()->withErrors(['Alias ' . $request->alias . ' is not supported'])->withInput();
# Download
return (new ProductExport((int) $request->id))->download('iezon_solutions_' . $request->alias . '_' . $request->id . '.xlsx');
}
When I head over to https://example.com/excel/release?alias=product_list&id=1 this executes correctly and returns an excel file. However, there is no column headers for the rows. The data comes out like so:
1 150 1 3 2019-01-16 16:37:25 2019-01-16 16:37:25 10
However, this should contain column headers like ID, cost etc... How can I include the column headers in this output?
According to documentation you can change your class to use the WithHeadings interface, and then define the headings function to return an array of column headers:
<?php
namespace App;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromQuery, WithHeadings
{
use Exportable;
public function __construct(int $id)
{
$this->id = $id;
}
public function query()
{
return ProductList::query()->where('id', $this->id);
}
public function headings(): array
{
return ["your", "headings", "here"];
}
}
This works with all export types (FromQuery, FromCollection, etc.)
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use DB;
class LocationTypeExport implements FromCollection,WithHeadings
{
public function collection()
{
$type = DB::table('location_type')->select('id','name')->get();
return $type ;
}
public function headings(): array
{
return [
'id',
'name',
];
}
}
You can combine this with array_keys to dynamically get your column headers:
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromQuery, WithHeadings
{
use Exportable;
public function __construct(int $id)
{
$this->id = $id;
}
public function query()
{
return ProductList::query()->where('id', $this->id);
}
public function headings(): array
{
return array_keys($this->query()->first()->toArray());
}
}
If you're using it with a collection, you can do so like the following:
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class ProductExport implements FromCollection, WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
// for selecting specific fields
//return ProductList::select('id', 'product_name', 'product_price')->get();
// for selecting all fields
return ProductList::all();
}
public function headings(): array
{
return $this->collection()->first()->keys()->toArray();
}
}
<?php
namespace App\Exports;
use App\Models\UserDetails;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class CustomerExport implements FromCollection, WithHeadings
{
public function collection()
{
return UserDetails::whereNull('business_name')
->select('first_name','last_name','mobile_number','dob','gender')
->get();
}
public function headings() :array
{
return ["First Name", "Last Name", "Mobile","DOB", "Gender"];
}
}
<?php
namespace App\Exports;
use App\Models\StudentRegister;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class StudentExport implements FromCollection, WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return StudentRegister::select('name','fname','mname','gender','language','address')->get();
}
public function headings(): array
{
//Put Here Header Name That you want in your excel sheet
return [
'Name',
'Father Name',
'Mother Name',
'Gender',
'Opted Language',
'Corresponding Address'
];
}
}
I am exporting from Collections and I wanted to generate headings automatically from the column names. The following code worked for me!
public function headings(): array
{
return array_keys($this->collection()->first()->toArray());
}
If you want to manually write the column names return an array with the column names.
And don't forget to impliment WithHeadings Interface
Thanks #Ric's comment.
This code works for me
use App\Newsletter;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class NewsletterExport implements FromCollection, WithHeadings
{
public function headings(): array
{
return [
'Subscriber Id',
'Name',
'Email',
'Created_at',
];
}
public function collection()
{
return Newsletter::where('isSubscribed', true)->get(['id','name','email','created_at']);
}
}

How do filter plans with or without trial on Stripe with Laravel 5?

I want to retrieve this.
all plan.
all plan without Trial Day.
all plan only trial day.
but i don't know the procedure for take a filter on api Stripe.
https://stripe.com/docs/api#plans
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Stripe\Plan;
use Stripe\Stripe;
class PlanController extends Controller {
public function index(Request $request)
{
Stripe::setApiKey(env('STRIPE_SECRET'));
$param = ['limit' => 20];
$opt = ['livemode' => false];
$plans = Plan::all($param,$opt);
return plans;
}
}
After you fetch all, you can filter it through php
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Stripe\Plan;
use Stripe\Stripe;
class PlanController extends Controller {
public function index(Request $request)
{
Stripe::setApiKey(env('STRIPE_SECRET'));
$param = ['limit' => 20];
$opt = ['livemode' => false];
$all_plans = Plan::all($param,$opt);
$trial_plans = [];
$no_trial_plans = []
foreach ($all_plans['data'] as $plan) {
if ($plan['trial_period_days'] == null) {
$no_trial_plans[] = $plan;
}
else {
$trial_plans[] = $plan;
}
}
return [$all_plans, $trial_plans, $no_trial_plans];
}
}

How to return data with Laravel 5

I have problem with method AjaxController::InsertComment($comment,$name); not return $id variable into my ajax.bade.php.
It insert data into database correctly but not return...
Here is my Ajax Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AjaxController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('ajax.ajax');
}
public static function InsertComment($comment,$name){
$qv = DB::table('comments')->insert(
array(
'name' => $name,
'comments_text' => $comment
)
);
//$id = DB::table('comments')->insertGetId(array('name' => 'john#example.com', 'comments_text' => 'asdasdsa'));
$id = DB::getPdo()->lastInsertId();
return $id;
}
}
Ok, I think I got you now. Suppose we have the following:
Example: ajax.blade.php
<div>{{ "Hi" }} </div>
<script>
$.post('/ajax', {
'_token': $('meta[name=csrf-token]').attr('content'),
task: "comment_insert",
userID: _userID,
comment: _comment,
name: _name,
userName: _userName,
date: _date
}).done(function( data ) {
alert( "ID Loaded: " + data );
});
</script>
Your controller should read like:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AjaxController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('ajax.ajax');
}
public static function InsertComment($comment,$name)
{
$id = DB::table('comments')
->insertGetId(array(
'name' => $name,
'comments_text' => $comment
));
return $id;
}
}

Categories