Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Uploading files via API

Premium
3:24

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 of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

LS
Luis Scura ✓ Link copied!

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

N
Nerijus ✓ Link copied!

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