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...
Is it necessary to return the "photo" in the category resource JSON for the frontend to know that there is a photo field?
How else frontend will know about field if you dont pass it? Every field must be passed which you need
You would make this field available if an external site is consuming your api for an index listing so they can apply this image. Not necessary if you don't want anything consuming your api to use the photo.