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...