The case is simple: I need to generate a txt in Laravel based on Array and then attach this text file with Attachments through Mail :: to (!)
The case is simple: I need to generate a txt in Laravel based on Array and then attach this text file with Attachments through Mail :: to (!)
Step by step to create a text file and send via email to laravel is:
First thing is to set up the FileSystem folder of the storage
folder with the command:
This will create a folder inside the folder public
, which is a way to organize your folders in the laravel and put your files inside it, eg:
itiswithinthisfolderthatthefilescreated.txt
willbesavedfromsomearray
of php .
Now it is to create a text file ( .txt
) with some values of array
, example :
$array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
$t = "";
foreach ($array as $i)
{
$t .= $i . PHP_EOL;
}
and soon after to save in the storage
folder the text file do:
\Illuminate\Support\Facades\Storage::disk('public')->put('400.txt', $t);
Note that Facade Storage
has a disk
with the name of public
which is the setting contained in app\config\filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
This setting is responsible for telling the storage location that is the same as the link
created from the storage
folder, and do not worry this is already configured.
The put
method finally creates a text file with the array
data that is now contained in the $t
variable.
Type in the command line:
php artisan make:mail MailTxt
A class and configuration for sending the email is created, as follows:
<?php namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class MailTxt extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
//
}
public function build()
{
return $this->view('email_txt')
->from('[email protected]')
->attach(public_path('/storage/400.txt'));
}
}
In the build()
method we will configure the following methods:
view
: view name which is the main layout of your email
from
: who is sending the email would be the email address
attach
: the text file that was previously created to be attached
With these 3 steps an email with its text attachment is sent.
Full Code:
$array = [
1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20
];
$t = "";
foreach ($array as $i)
{
$t .= $i . PHP_EOL;
}
\Illuminate\Support\Facades\Storage::disk('public')->put('400.txt', $t);
\Illuminate\Support\Facades\Mail::to("[email protected]")->send(new \App\Mail\MailTxt());