Level 33
Are you going to have a fixed number of images on your homepage? Or will it be variable?
I'd like to upload multiple images as preview for the front page and store the links in db. What come across to my mind is to store each link into each columns, is that good practice?or put in one column and separated with comma separator?
In that case I would create a dedicated model and table for the Previews.
Here's a adapted/simplified version of what I recently did in one of my projects:
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Preview extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'unique_filename', 'original_filename', 'size', 'mime_type',
];
/**
* Boot the model.
*
* @return void
*/
public static function boot()
{
parent::boot();
self::deleting(function(Preview $preview) {
$filePath = $preview->getFilePath();
if (Storage::exists($filePath)) {
Storage::delete($filePath);
}
});
}
/**
* Get the preview's file path.
*
* @return string
*/
public function getFilePath()
{
return sprintf("previews/%s",
$this->unique_filename
);
}
}
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePreviewsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('previews', function (Blueprint $table) {
$table->id();
$table->string('unique_filename')->unique();
$table->text('original_filename');
$table->bigInteger('size')->unsigned();
$table->string('mime_type');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
Let me know if you need help implementing the upload functionality.
Please or to participate in this conversation.