Our Customer needs some documents to be uploaded. These can range from simple information sheets to signed PDF documents. We need to be able to upload them and add notes to them, just like this:
In this lesson, we will do the following:
- Create Documents database table, model
- Add Documents to the Customer form - only for edit page
- As a bonus, we will clean up the form a bit
- Add Documents to the Customer view page as downloadable links
Creating Database Table and Model
Our Documents will have the following fields:
-
id
-
customer_id
-
file_path
-
comments
(nullable text)
Let's start with the migration:
Migration
use App\Models\Customer; // ... Schema::create('documents', function (Blueprint $table) { $table->id(); $table->foreignIdFor(Customer::class)->constrained(); $table->string('file_path'); $table->text('comments')->nullable(); $table->timestamps();});
Then, we will create the model:
app/Models/Document.php
use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Storage; class Document extends Model{ protected $fillable = [ 'customer_id', 'file_path', 'comments' ]; protected static function booted(): void { self::deleting(function (Document $customerDocument) { Storage::disk('public')->delete($customerDocument->file_path); }); } public function customer(): BelongsTo { return $this->belongsTo(Customer::class); }}
Quick note: Look at our deleting
observer - we delete the file from the storage when the document is deleted. This is an excellent practice to follow.
And lastly, we need to tie our Customer model to the Document model:
// ... public function documents(): HasMany{ return $this->hasMany(Document::class);}
Adding Documents to the Customer Form
Adding Documents to the Customer form is...