To force file downloads in a Laravel project using Inertia with Vue 3 and the Composition API, you can create a route that handles the file download and use the response()->download() method to force the download.
Here's an example of how you can achieve this:
- Define a route in your
web.phpfile that points to a controller method:
Route::get('/download-file/{filename}', [FileController::class, 'download'])->name('download.file');
- Create a
FileControllerwith adownloadmethod that handles the file download:
use Illuminate\Support\Facades\Storage;
class FileController extends Controller
{
public function download($filename)
{
$path = Storage::disk('public')->path($filename);
return response()->download($path);
}
}
- In your Vue component, you can create a link that triggers the file download:
<template>
<a :href="downloadUrl" download>Download File</a>
</template>
<script>
import { computed } from 'vue';
import { useRoute } from 'vue-router';
export default {
setup() {
const route = useRoute();
const downloadUrl = computed(() => {
return route.resolve({ name: 'download.file', params: { filename: 'your-file-name.ext' } });
});
return {
downloadUrl,
};
},
};
</script>
Make sure to replace 'your-file-name.ext' with the actual filename you want to download.
This solution bypasses the need to use the Inertia.get() method and directly triggers the file download using a regular route and the response()->download() method.