PHP code example of nurbekjummayev / laravel-media-api

1. Go to this page and download the library: Download nurbekjummayev/laravel-media-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nurbekjummayev / laravel-media-api example snippets


// migration
Schema::create('product_photos', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained()->cascadeOnDelete();
    $table->foreignId('media_id')->constrained('media');
    $table->integer('sort')->default(0);
});

// after saving the links:
app(\NurbekJummayev\LaravelMediaApi\Services\MediaService::class)->markAttached($mediaIds);

// migration: $table->foreignId('cover_media_id')->nullable()->constrained('media');
$product->cover_media_id = $request->integer('cover_media_id'); // validate exists:media,id
$product->save();
app(\NurbekJummayev\LaravelMediaApi\Services\MediaService::class)->markAttached([$product->cover_media_id]);

use NurbekJummayev\LaravelMediaApi\Concerns\InteractsWithMedia;

class Product extends Model
{
    use InteractsWithMedia;

    // FK columns holding a media id → auto-marked attached on save,
    // and deleted when the model is deleted:
    protected function mediaColumns(): array
    {
        return ['cover_media_id'];
    }

    // Pivot media relations → cleaned up (detached + deleted) on model delete:
    protected function mediaRelations(): array
    {
        return ['photos'];
    }

    public function photos(): BelongsToMany
    {
        return $this->belongsToMany(Media::class, 'product_photos');
    }
}

$product->cover_media_id = $id;
$product->save();                  // cover media → attached=true automatically

$product->syncMedia('photos', $ids); // pivot sync + attached=true

$media->owner; // belongsTo config('media.owner_model')
bash
composer update nurbekjummayev/laravel-media-api
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-media-api-config"
bash
php artisan media:purge --hours=24