Courses

How to Build Laravel 11 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...

The full lesson is only for Premium Members.
Want to access all 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord