Home > database >  Laravel protect audio file from direct url and show on blade view
Laravel protect audio file from direct url and show on blade view

Time:05-16

I have a form with uploading audio mp3.

I need to protect these audio files from direct access from url, accessible only logged users.

Added a new storage disk in > filesystem.php

     'audio' => [
        'driver' => 'local',
        'root' => storage_path('app/private/audio/'),
     ],

Added a new route in > web.php

Route::get('/private/audio/{audio}', [AudioController::class, 'index']);

AudioController

public function __construct()
{
    $this->middleware('auth');
}

public function index($audio)
{

    $path = "/private/audio/{$audio}";

    if(Storage::exists($path)) {
         return Storage::download($path);
    }

    abort(401);
    
}

Now if i get on follow url, my audio will download only for logged users, so works fine.

https://example.com/private/audio/my_audio_file.mp3

So how can I access to audio file in a blade view for logged users only.

@foreach($files as $file)
   <audio preload="none" src="{{ asset('audio/private/') }}/{{ $file->file_name }}.mp3" controlslist="nodownload" type="audio/mp3">
  </audio>
@endoforeach

Is there a way for get this?

CodePudding user response:

It works fine after doing the optimize command:

php artisan optimize

CodePudding user response:

@foreach($files as $file)
@if(Auth::check())
<audio preload="none" src="{{ asset('audio/private/') }}/{{ $file->file_name }}.mp3" controlslist="nodownload" type="audio/mp3"></audio>
@else
Login to access audio
@endif
@endforeach
  • Related