Skip to main content

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? (30 h 21 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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.