I'm working on adding media uploads to my custom CMS. To do this, I have tried multiple forms of the same upload function. When I click upload, the error says 'image' is a required field even with a file inside the field. Below, I have my model, view, controller, and migration to provide insight on how I am trying to upload media.
Media.php (Model)
class Media extends Model
{
use HasFactory;
protected $fillable = ['name', 'path', 'alt', 'user_id'];
}
MediaController.php (Controller)
class MediaController extends Controller
{
public function index()
{
$uploads = Media::get();
$users = User::get();
return view('admin.media.index', compact('uploads', 'users'));
}
public function create()
{
return view('admin.media.upload');
}
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
]);
$name = $request->file('image')->getClientOriginalName();
$path = $request->file('image')
->store('public/img/media/' . date("Y/M"));
$upload = new Media;
$upload->user_id = Auth::id();
$upload->name = $name;
$upload->path = $path;
$upload->alt = $request->alt;
$upload->save();
return redirect()->route('admin.media.index')
->with('success', 'Media uploaded successfully');
}
}
upload.blade.php (View)
@extends('layouts.admin.app')
@section('title', 'Upload Media')
@section('content')
<section class="my-4">
<h3>{{ __('Media')}} | {{ __('Upload New Media') }}</h3>
<a class="btn btn-warning" href="{{ route('admin.media.index') }}"> {{ __('Go Back To Media')}}</a>
</section>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<div class="flex">
<form action="{{ route('admin.media.store') }}" enctype="multipart/form-data" method="POST" class="w-full">
@csrf
<div class="flex">
<div class="w-full md:w-3/4">
<x-general.form.group class="">
<input type="file" name="file" class="form-control" id="image">
@error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</x-general.form.group>
<button type="submit" class="btn btn-dark w-full" value="{{ __('Upload Media')}}"/>
</div>
<div class="w-full md:w-1/4">
<x-general.form.group class="">
<img src="" id="image_preview" alt="Upload Preview" class=""/>
<x-admin.general.forms.label for="alt" label="{{ __('Alt Text')}}" class="small"/>
<input type="text" name="alt" id="alt" class="" value=""/>
@error('alt')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</x-general.form.group>
</div>
</div>
</form>
</div>
@endsection
The error appears because there is no
<input>
element withname="image
. Your file upload field hasname="file"
. Changeto