Courses

How to Build Laravel 12 API From Scratch

Uploading files via API

Summary of this lesson:
- File upload handling in Laravel API
- File storage configuration

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/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
 
// ...
 
],
 
// ...
 
];

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.

Previous: Finishing CRUD: Update, Delete and Resource Controller
avatar

Is it necessary to return the "photo" in the category resource JSON for the frontend to know that there is a photo field?

avatar

How else frontend will know about field if you dont pass it? Every field must be passed which you need

avatar
You can use Markdown
avatar

You can also store a photo like this:

$data['photo'] = $request->photo->store('categories', 'public');
avatar
You can use Markdown
avatar
You can use Markdown