I'm trying to create a validator to my form input, to only accept images. I've searched here on stack and other forums, but all the answers that i got didn't work for me.. Most of the answers where syntax erros of the lack of enctype="multipart/form-data".. but that is not the case here, aparently.. Here is my form and my controller:
Form:
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
@csrf
<div >
<input type="file" name="filenames[]" >
<div >
<button type="button" style="width: 100px !important"><i ></i>Add</button>
</div>
</div>
<div >
<div style="margin-top:10px">
<input type="file" name="filenames[]" >
<div >
<button type="button" style="width: 100px !important"><i ></i> Remove</button>
</div>
</div>
</div>
<button type="submit" style="margin-top:10px">Submit</button>
</form>
<?php
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('create');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'filenames' => 'mimetypes:jpeg,png,jpg',
'filenames.*' => 'required'
],$messages = [
'required' => 'The :attribute field is required.',
'mimes' => 'Apenas jpeg, png, png são permitidos.'
]
);
$files = [];
if($request->hasfile('filenames'))
{
foreach($request->file('filenames') as $file)
{
$name = time().rand(1,100).'.'.$file->extension();
$file->move(public_path('files'), $name);
$files[] = $name;
}
}
$file= new File();
$file->filenames = $files;
$file->save();
return back()->with('success', 'Data Your files has been successfully added');
}
}
I've tried to change the validation to this: 'mimes:jpeg,png |max:4096, required',
, but still not working..
CodePudding user response:
Use like this
$rules = array(
'filenames' => 'required|array',
'filenames.*' => 'image|mimes:jpg,jpeg'
);