Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel migration for update from v4 to v5 of Spatie Medialibrary
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
class AddMimeTypeToMediaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('media', function (Blueprint $table) {
$table->string('mime_type')->after('file_name')->nullable();
});
DB::transaction(function () {
$images = DB::table('media')
->select('id', 'file_name', 'disk')
->get();
foreach ($images as $img) {
$prefix = Storage::disk($img->disk)->getDriver()->getAdapter()->getPathPrefix();
$mime_type = (new Finfo(FILEINFO_MIME_TYPE))->file($prefix.'/'.$img->id.'/'.$img->file_name);
DB::table('media')
->where('id', $img->id)
->update(['mime_type' => $mime_type]);
}
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('media', function (Blueprint $table) {
$table->dropColumn('mime_type');
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.