Back to Course |
How to Build Laravel 11 API From Scratch

Uploading files via API

In this lesson, let's talk about uploading files.

For this example, I have created a new photo field for the categories table.

database/migrations/xxx_add_photo_to_categories_table.php:

Schema::table('categories', function (Blueprint $table) {
$table->string('photo')->nullable();
});
class Category extends Model
{
use HasFactory;
 
protected $fillable = ['name', 'photo'];
}

From the backend, there is no difference for uploading files.

app/Http/Controllers/Api/CategoryController.php:

use Illuminate\Support\Str;
 
class CategoryController extends Controller
{
// ...
 
public function store(StoreCategoryRequest $request)
{
$data = $request->all();
 
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$name = 'categories/' . Str::uuid() . '.' . $file->extension();
$file->storePubliclyAs('public', $name);
$data['photo'] = $name;
}
 
$category = Category::create($data);
 
return new CategoryResource($category);
}
 
// ...
}

In the store method, we upload a standard file to a public disk. There are multiple ways to handle file uploads, like using spate/laravel-medialibrary package. Here is a simple example showing that from the backend part nothing changes if you are working on the API.

The main question is passing the file from the frontend or the mobile application. That is the job for the frontend. In our case, let's try in the client.

In the client, we can choose the value field as file instead of text.

Where the file is stored, it is set in the config/filesystems.php.

return [
 
'default' => env('FILESYSTEM_DRIVER', 'local'),
 
'disks' => [
 
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
 
// ...
 
],
 
// ...
 
];

We can see the file is uploaded.

Since this course isn't about Vue.js, you can read an article Laravel API: How to Upload File from Vue.js about how to upload files in Vue.js.