Recently, in a project on Laravel + Eloquent, I needed to make printable forms of documents - invoices, contracts in Word format. Since there are many different documents in the system, I decided to make it universally so that it could later be used in other projects.
As a result, we got an implementation that requires a minimum cost of integration into the project.
As I used to make printable forms. Used different approaches
- .
- .
- html word.
- , , .
. Eloquent, , .
,
composer require mnvx/eloquent-print-form
Eloquent, . , .
use Illuminate\Database\Eloquent\Model;
/**
* @property string $number
* @property string $start_at
* @property Customer $customer
* @property ContractAppendix[] $appendixes
*/
class Contract extends Model
{
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function appendixes()
{
return $this->hasMany(ContractAppendix::class);
}
}
/**
* @property string $name
* @property CustomerCategory $category
*/
class Customer extends Model
{
public function category()
{
return $this->belongsTo(CustomerCategory::class);
}
}
/**
* @property string $number
* @property string $date
* @property float $tax
*/
class ContractAppendix extends Model
{
public function getTaxAttribute()
{
$tax = 0;
foreach ($this->items as $item) {
$tax += $item->total_amount * (1 - 100 / (100+($item->taxStatus->vat_rate ?? 0)));
}
return $tax;
}
}
,
(Contract
), (Customer
), . (ContractAppendix
).
— . docx
Eloquent. , , , ${customer.category.name}
.
, |
, ${number|placeholder}
. , , ${start_at|date|placeholder}
.
placeholder
— "____",date
— 24.12.2020,dateTime
— - 24.12.2020 23:11,int
— 2`145,decimal
— 2`145.07.
. ${entities.#row_number}
.
Now that the document is described, it remains to simply start generating the printable
use Mnvx\EloquentPrintForm\PrintFormProcessor;
$entity = Contract::find($id);
$printFormProcessor = new PrintFormProcessor();
$templateFile = resource_path('path_to_print_forms/your_print_form.docx');
$tempFileName = $printFormProcessor->process($templateFile, $entity);
The generated file $tempFileName
will contain a prepared printable.
In a Laravel project, the controller method responsible for generating the printable might look like this
public function downloadPrintForm(FormRequest $request)
{
$id = $request->get('id');
$entity = Contract::find($id);
$printFormProcessor = new PrintFormProcessor();
$templateFile = resource_path('path_to_print_forms/your_print_form.docx');
$tempFileName = $printFormProcessor->process($templateFile, $entity);
$filename = 'contract_' . $id;
return response()
->download($tempFileName, $filename . '.docx')
->deleteFileAfterSend();
}
Summing up, I will say that I decently offloaded myself by making this small library in a project with a lot of printable forms. I do not need to write my own unique code for each of them. I just describe the variables as above and get the result very quickly. I will be glad if the package will help you to save time.