My controller is like this :
public function add($param)
{
...
$message = Message::create([
...
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
Notification::send($notify_to, new MessageInsert($message));
dd($message);
return $message;
}
My MessageInsert is like this :
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MessageInsert extends Notification implements ShouldBroadcast, ShouldQueue
{
use Queueable;
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function via($notifiable)
{
return ['broadcast','database','mail'];
}
public function toArray($notifiable)
{
return [
'id' => $this->data->id,
...
];
}
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Hello!')
->line('...')
->action('...')
->line('Thank you!');
}
}
If like this :
return ['broadcast','database','mail'];
The result of dd($message); is error
But if like this :
return ['database','mail'];
The result of dd($message); is array of $message
Why there is error when I use broadcast?
Did you try adding the toBroadcast function?
public function toBroadcast($notifiable) {
return new BroadcastMessage([ 'invoice_id' => $this->invoice->id, 'amount' => $this->invoice->amount, ]);
}
Related
I use code below for import all models at the same time from different excel files.
It works well on Laravel 7.
But when I move it to Laravel 8, I always get error PDOException There is no active transaction
I see in DB that only one import of News model is done.
I cannot understand the reason of this problem. Documentation seems the same and there is no help in guthub.
App\Admin\routes.php
$router->get('seed', 'SeedController#index')->name('admin.seed');
App\Admin\Controllers\SeedController.php
<?php
namespace App\Admin\Controllers;
use Illuminate\Support\Facades\DB;
use App\Imports\Feedback\FeedbackImport;
use App\Imports\News\NewsImport;
use App\Imports\Menu\MenuImport;
use Maatwebsite\Excel\Facades\Excel;
class SeedController extends BaseAdminController
{
public $feedback;
public $news;
public $menu;
public function __construct()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
$this->feedback = new FeedbackImport();
$this->news = new NewsImport();
$this->menu = new MenuImport();
}
public function index(Content $content)
{
$this->import();
$feedback = $this->feedback;
$news = $this->news;
$menu = $this->menu;
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
return $content
->title('Import & Export')
->description('Laravel excel')
->view('admin.seed', compact('menu', 'news', 'feedback'))
->withSuccess('Import succesfully finished');
}
public function import()
{
Excel::import($this->feedback, 'import/feedback.xlsm');
Excel::import($this->news, 'import/news.xlsm');
Excel::import($this->menu, 'import/menu.xlsm');
}
}
App\Imports\Feedback\FeedbackImport.php
<?php
namespace App\Imports\Feedback;
use App\Models\Feedback;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\AfterSheet;
class FeedbackImport implements ToModel, WithHeadingRow, WithEvents
{
use RegistersEventListeners;
public $rows = 0;
public function model(array $row)
{
++$this->rows;
return new Feedback([
'name' => $row['name'],
'rate' => $row['rate'],
'text' => $row['text'],
]);
}
public function getRowCount(): int
{
return $this->rows;
}
public static function beforeSheet(BeforeSheet $event)
{
app('log')->info('Feedback import started');
Feedback::truncate();
}
public static function afterSheet(AfterSheet $event)
{
app('log')->info('Feedback import finished');
}
}
App\Imports\News\NewsImport.php
<?php
namespace App\Imports\News;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\AfterImport;
class NewsImport implements WithMultipleSheets, WithEvents
{
use RegistersEventListeners;
public $category;
public $post;
public function __construct()
{
$this->category = new NewsImportCategory();
$this->post = new NewsImportPost();
}
public function sheets(): array
{
return [
'news_categories' => $this->category,
'news_posts' => $this->post,
];
}
public static function beforeImport(BeforeImport $event)
{
app('log')->info('News import started');
}
public static function afterImport(AfterImport $event)
{
app('log')->info('News import finished');
}
}
App\Imports\News\NewsImportCategory.php
<?php
namespace App\Imports\News;
use App\Models\NewsCategory;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\AfterSheet;
class NewsImportCategory implements ToModel, WithHeadingRow, WithEvents
{
use RegistersEventListeners;
public $rows = 0;
public function model(array $row)
{
if (empty($row['id'])) { return null; }
++$this->rows;
return new NewsCategory([
'id' => $row['id'],
'parent_id' => $row['parent_id'],
'title' => $row['title'],
'description' => $row['description'],
]);
}
public function getRowCount(): int
{
return $this->rows;
}
public static function beforeSheet(BeforeSheet $event)
{
app('log')->info('NewsCategory import started');
NewsCategory::truncate();
}
public static function afterSheet(AfterSheet $event)
{
app('log')->info('NewsCategory import finished');
}
}
App\Imports\News\NewsImportPost.php
<?php
namespace App\Imports\News;
use App\Models\NewsPost;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\AfterSheet;
class NewsImportPost implements ToModel, WithHeadingRow, WithEvents
{
use RegistersEventListeners;
public $rows = 0;
public function model(array $row)
{
if (empty($row['category_id'])) { return null; }
++$this->rows;
return new NewsPost([
'category_id' => $row['category_id'],
'title' => $row['title'],
'fulltext' => $row['fulltext'],
'image' => $row['image'],
]);
}
public function getRowCount(): int
{
return $this->rows;
}
public static function beforeSheet(BeforeSheet $event)
{
app('log')->info('NewsPost import started');
NewsPost::truncate();
}
public static function afterSheet(AfterSheet $event)
{
app('log')->info('NewsPost import finished');
}
}
Menu is almost same as News import.
I'm following this example from the docs to handle multiple sheets import.
My Controller:
public function import(Request $request) {
$file = $request->file('import')->store('/storage');
$import = new MultisheetContactsImport();
$import->import($file);
if ($import->failures()->isNotEmpty()) {
return $import->failures();
}
return $import->getRowCount();
}
My import class ContactsImport.php
namespace App\Imports;
use App\Models\Email;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\withHeadingRow;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Facades\Validator;
use Throwable;
class ContactsImport implements ToModel, withHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure
{
private $rows = 0;
use Importable, SkipsErrors, SkipsFailures;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
++$this->rows;
return new Email([
'apiKey' => Str::random(16),
'firstname' => $row['firstname'],
'lastname' => $row['lastname'],
'emailAddress' => $row['emailaddress'],
'businessType' => $row['businesstype'],
'allowed' => true,
'updates' => true,
'marketing' => true,
]);
}
public function getRowCount(): int
{
return $this->rows;
}
public function rules(): array
{
return [
'*.emailaddress' => ['email', 'unique:emails,emailaddress']
];
}
}
My Multisheet import class MultisheetContactsImport.php
class MultisheetContactsImport extends ContactsImport implements WithMultipleSheets
{
public function sheets(): array
{
return [
'Contacts' => new ContactsImport()
];
}
}
The methods failures and and getRowCount work fine if I use the ContactsImport class without multisheets however now I only get a response 0
Just Wrap your import line code with try catch block it should handle every thing:
try {
$master = Excel::import(new MasterImport($auth), $request->file('master_upload'));
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
dd($failures);
foreach ($failures as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
}
You can add this method on you ImportClass
/**
* #param Failure ...$failures
* #throws ValidationException
*/
public function onFailure(Failure ...$failures)
{
$exception = ValidationException::withMessages(collect($failures)->map->toArray()->all());
throw $exception;
}
User Laravel Validation Exeption
use Illuminate\Validation\ValidationException;
and than on the view display validation messages:
#if(count($errors->getMessages()) > 0)
<div class="alert alert-danger alert-dismissible" role="alert">
<strong>Validation Errors:</strong>
<ul>
#foreach($errors->getMessages() as $errorMessages)
#foreach($errorMessages as $errorMessage)
<li>
{{ $errorMessage }}
×
</li>
#endforeach
#endforeach
</ul>
</div>#endif
I am beginner webdeveloper,
I use in my project Laravel 7 and maatwebsite/excel
I have this code:
namespace App\Models;
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
return $res;
}
}
public function export(Request $request)
{
return Excel::download(new ReservationExport($request->input('query')), 'reservation-'.$request->input('query').'.xlsx');
}
This code generates an Excel document. It works fine. I would like to add a sequence number in 1 column (1,2,3 etc).
How can I do this?
My model:
class Reservation extends Model
{
protected $quarded = ['id'];
protected $fillable = ['email', 'token', 'date', 'hour', 'track', 'sex', 'time', 'people'];
public $timestamps = true;
protected $table = 'reservations';
}
Please help
try this
basically u need to add sn to heading then in your collection u need to a new key sn with calculated sequence number
hope it will work if not please tell me what error u r getting
<?php
use App\Models\Reservation;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;
class ReservationExport implements FromCollection, WithHeadings
{
use Exportable;
protected $date;
public function __construct(string $date)
{
$this->date = $date;
}
public function headings(): array
{
return [
'SN', // sn new key adding
'LP',
'ID Rezerwacji',
'Adres email',
'Token',
'Data',
'Godzina',
'Tor',
'Płeć',
];
}
public function collection()
{
$res = Reservation::select('id', 'id', 'email', 'token', 'date', 'hour', 'track', 'sex')->where('date', $this->date)->orderBy('time', 'ASC')->orderBy('track', 'ASC')->get();
foreach ($res as $val) {
$val->sex = ($val->sex == 1) ? 'kobieta' : 'mężczyzna';
}
$res->map(function ($row,$key) {
return $row['sn'] = $key; // sn key added to collection
});
return $res;
}
}
I am generating a Excel Export, I want to change the timestamps format in excel file from 2020-07-29 13:56:09 to just DD:MM:YYYY.
How can I change my Export Class to Format the timestamp Column in my Excel File, BTW Date is in 'E' column in Excel file.
My Export Class:
use App\outbound_detail;
use App\outbound_temp;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Events\AfterSheet;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
protected $reference;
function __construct($reference)
{
$this->reference = $reference;
}
public function collection()
{
return outbound_detail::where('reference', $this->reference)->get([
'reference', 'sku_parent', 'sku_child', 'cases', 'updated_at'
]);
}
public function headings(): array
{
return [
'Reference',
'SKU Parent',
'SKU Child',
'Cases Released',
'Date Created'
];
}
// ...
/**
* #return array
*/
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
On your Reference Model, add this :
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d:m:Y');
}
You can use it's column formatting.
Try this:
// ...
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class ReleaseExportView implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithColumnFormatting
{
// ...
public function map($reference): array
{
return [
$reference->reference,
$reference->sku_parent,
$reference->sku_child,
$reference->cases,
Date::dateTimeToExcel($reference->updated_at)
];
}
public function columnFormats(): array
{
return [
'E' => NumberFormat::FORMAT_DATE_DDMMYYYY
];
}
}
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('/');
}
}