I tried to upload multiple images using validation system, even I upload the jpeg type images it gives me validation system error The images must be a file of type: jpeg, jpg, png, gif, svg.
register.blade.php
<form method="POST" action="{{ route('register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group" id="divim">
<label>photos<span class="text-hightlight">*</span></label>
<input class="form-control" type="file" name="images[]" value="{{ old('images') }}" multiple>
#error('images')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</form>
RegisterController.php
protected function validator(array $data)
{
return Validator::make($data, [
'images' => ['bail','required','mimes:jpeg,jpg,png,gif,svg','max:2048']
]);
}
method create/store
protected function create(array $data)
{
$dataim = array();
if($request->hasFile('images'))
{
foreach($request->file('images') as $file)
{
$namee = encrypt($file->getClientOriginalName()).'.'.$file->extension();
//$name = encrypt($namee).'.'.$file->extension();
$name = "profiles\\".$jdate->format('F').$jdate->year."\\".$namee;
$file->storeAs("public\\profiles\\".$jdate->format('F').$jdate->year, $namee);
//$Annonce->images = "annonces\\".$jdate->format('F').$jdate->year."\\".time().'.'.$image->extension();
array_push($dataim,$name);
}
}
$user->images=json_encode($dataim);
$imm =$user->images;
return User::create([
'images' => $imm
]);
}
Since you want to validate an array, you have to structure your rules differently:
return Validator::make($data, [
'images' => ['bail', 'required', 'array', 'min:1'],
'images.*' => ['bail', 'mimes:jpeg,jpg,png,gif,svg', 'max:2048'],
]);
See the docs on validating arrays for more information.
Related
I am creating a Laravel crud. in here i have a DB table called:
File:
'title','description_short','description_long,'file','language'
the problem lays in the 'file' column. here i can upload files like word and excel. but whenever i edit a row with a file attached. the file gets removed if i don't upload A or THE file again.
edit.blade:
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3"> {{('Editing files')}}</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br />
#endif
#if(empty($fileEdit))
<div>{{('Choose file to edit')}}</div>
#else
<form method="post" action="{{ route('admin.file.update', $fileEdit->id) }}">
#method('PUT')
#csrf
<div class="form-group">
<label for="name">{{('title')}}</label>
<input type="text" class="form-control" name="title" value="{{ $fileEdit->title }}" />
</div>
<div class="form-group">
<label for="name"> {{('Short description')}}</label>
<input type="text" class="form-control" name="description_short" value="{{ $fileEdit->description_short }}" />
</div>
<div class="form-group">
<label for="name"> {{('Long description')}}</label>
<input type="text" class="form-control" name="description_long" value="{{ $fileEdit->description_long }}" />
</div>
<div class="form-group">
<label for="name"> {{('file')}}</label>
<input type="file" class="form-control" name="file" value="{{ $fileEdit->file }}" />
</div>
<div class="form-group">
<label for="name">{{('language')}}</label>
<select name="language_id" class="form-control">
#foreach($languages as $language)
<option value=" {{$language->id}}">{{$language->name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
#endif
</div>
</div>
controller:
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\File;
use App\Models\Language;
class FileController extends Controller
{
public function index()
{
$files = File::with('language')->get();
$languages = Language::all();
return view('admin.file.index', compact('files', 'languages'));
}
public function create()
{
//
}
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$file = new File([
'title'=> $request->get('title'),
'description_short'=> $request->get('description_short'),
'description_long'=> $request->get('description_long'),
'file'=>$request->get('file'),
'language_id'=> $request->language_id,
]);
$file->save();
return back();
}
public function show($id)
{
//
}
public function edit($id)
{
$files = File::all();
$fileEdit = File::find($id);
$languages = Language::all();
return view('admin.file.index', compact('files', 'fileEdit', 'languages'));
}
public function update(Request $request, $id)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileData = [
'title'=> $request->title,
'description_short'=> $request->description_short,
'description_long'=> $request->description_long,
'file'=>$request->file,
'language_id'=> $request->language_id,
];
File::whereId($id)->update($fileData);
return redirect()->route('admin.file.index');
}
public function destroy($id)
{
$file = File::find($id);
$file->delete();
return redirect()->route('admin.file.index');
}
}
File model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
public function language(){
return $this->belongsTo(Language::class);
}
protected $table = 'file';
protected $fillable = [
'title',
'description_short',
'description_long',
'file',
'language_id',
'user_id',
];
}
for security reasons, you can't set value of input type file. so
<input type="file" class="form-control" name="file" value="{{ $fileEdit->file }}" />
is not adding the old file in the input. what you can do is checking if user added any file in controller.
<input type="file" class="form-control" name="file" />
in controller
$fileData = [
'title' => $request->title,
'description_short' => $request->description_short,
'description_long' => $request->description_long,
'language_id' => $request->language_id,
];
if ($request->get('file')) {
$fileData['file'] = $request->file;
}
File::whereId($id)->update($fileData);
if you leave the validation field blank it may take the input as empty there for use bail which will not validation but the input should be empty. you will update with a data you are passing to validator.
$request->validate([
'title'=>'required',
'description_short'=>'bail',
'description_long'=>'bail',
'file'=>'bail',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileData = [
'title'=> $request->title,
'description_short'=> $request->description_short,
'description_long'=> $request->description_long,
'file'=>$request->file,
'language_id'=> $request->language_id,
];
File::whereId($id)->update($fileData);
make sure you have added file on fillable properties on File model
Try this
public function update(Request $request, $id)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileData = [
'title'=> $request->title,
'description_short'=> $request->description_short,
'description_long'=> $request->description_long,
'language_id'=> $request->language_id,
];
if (isset ($request->file)) {
$fileData['file'] = $request->file
}
File::whereId($id)->update($fileData);
return redirect()->route('admin.file.index');
}
I am getting data from backend and I want users to verify and update. What I am doing is passing the data from controller and fill them inside a form in view blade. When the user verifies the data and submit them, I pass them to validation in my method inside controller. As soon as the validation start laravel throws error:
\Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException",
"The GET method is not supported for this route. Supported methods:
POST.
Below is one the method in FormsController.php passing the variable that have been collected from database to view forms.oneedit.blade.php
public function editingone(Request $request)
{
$nameinst = $request->nameinst;
$firstnm = $request->firstnm;
$lastnm = $request->lastnm;
$phn = $request->phn;
$myArray['nameinst'] = $nameinst;
$myArray['firstnm'] = $firstnm;
$myArray['lastnm'] = $lastnm;
$myArray['phn'] = $phn;
return view('forms.oneedit', $myArray);
}
Below I receive the data in forms.oneedit.blade.php in view
<form class="w-full max-w-lg border-4 rounded-lg p-2" action="{{ route('updateeditedone.fomrone') }}" method="post">
#csrf
<input class="#error('firstname') border-red-500 #enderror"
id="firstname" name="firstname" type="text" value="{{ old('firstname', $firstnm) }}" required>
#error('firstname')
<div class="text-red-500 mt-2 text-sm">
{{ $message }}
</div>
#enderror
......................
<input class="
#error('lastname') border-red-500 #enderror"
id="lastname" name="lastname" type="text" value="{{ old('lastname', $lastnm) }}" required>
#error('lastname')
<div class="text-red-500 mt-2 text-sm">
{{ $message }}
</div>
#enderror
......................
<button type="submit">Submit</button> </form>
Below are among the routes in web.php
Route::post('/editone/formone', [FormsController::class,'editingone'])->name('edit.fomrone');
Route::post('/update/edited/formone', [FormsController::class,'updateeditedngone'])->name('updateeditedone.fomrone');
Below is the method that I am trying to validate the values in FormsController.php where the error occurs
public function updateeditedngone(Request $request)
{
$this->validate($request, [
'nameinstitute'=> 'required|max:255',
'firstname' => 'max:255',
'lastname' => 'max:255',
'phone' => 'required|max:255',
]); }
NB: If I remove the validation process inside the controller and just get the value it works, something like below:
$val = $request->nameinstitute;
dd($val);
With the above I correctly get the values before validation, But if I try to validate them first the error is thrown. Thanks in advance.
Update:
I have edited the validation method so as to direct to a certain view as suggested but still the same error
public function updateeditedngone(Request $request)
{
$validator = Validator::make($request->all(),
[ 'nameinstitute'=> 'required|max:255','firstname' => 'max:255',
'lastname' => 'max:255',
'phone' => 'required|max:255']);
if ($validator->fails())
{
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
dd($validator);
return redirect()->route('form.checkbtn');
php artisan view:clear php artisan cache:clear php artisan route:clear
Run it from CMD
It works for me
I want to upload a files to my laravel project. But I recognise that laravel randomly change my file name. How do I upload files to laravel without changing it's name. Also somehow my validation are not working. I just got redirected without any messages.
this are my blade
//show errors
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
/ul>
</div>
#endif
// forms
<form action="{{ route('designers.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group d-flex flex-column">
<label for="exampleInputFile">File input</label>
<input type="file" name="files[]" multiple>
</div>
<button type="submit">Submit</button>
</form>
this are my controller
$data = $request->validate([
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'file',
]);
if ($request->hasFile('files')) {
$allowedfileExtension=['pdf','jpg','png','docx','png','xlsx'];
$files = $request->file('files');
foreach ($files as $key => $value) {
$filename = $value->getClientOriginalName();
$extention = $value->getClientOriginalExtension();
$check = in_array($extention,$allowedfileExtension);
if ($check) {
File::create([
'name' => $value->store('designers','public'),
'type' => 'designer',
'project_id' => $data['project'],
'user_id' => Auth::user()->id,
]);
}
}
}
You can change your controller to this:
use Illuminate\Support\Facades\Storage;
function yourFunction(){
$this->validate($request,[
'project' => 'required|numeric',
'totalItem' => 'required|numeric',
'files' => 'nullable|array|file|mimes:pdf,jpg,png,docx,xlsx' //This validates file and MIME type. Also if it is not required, it should perhaps be nullable.
]);
if($request->hasFile('files'){
$files = $request->file('files');
foreach($files as $file){
$filename = $file->getClientOriginalName();
Storage::disk('local')->put($filename, file_get_contents($file)); //This stores your file.
}
}
//Save stuff to DB here
}
Official doc on file storage: https://laravel.com/docs/5.8/filesystem
Official doc on Validation of MIME: https://laravel.com/docs/5.8/validation#rule-mimes
I created custom login system on LARAVEL app, everything has worked perfectly until yesterday. When i typed in login form email and password for user that is same as from database, system redirect me back. I don't know what is problem, i cleared cache and everything but still it doesn't work. If someone know answer i would really appreciate.
Login page image:
https://imgur.com/a/xuEWQZg
Data of user stored in database whit seed :
https://imgur.com/0mJOviV
`
dd function with sent data from login form :
` https://imgur.com/a/D2k8Ztn
Main controller
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data = array(
'email' => $request->get('email'),
'password' => $request->get('password')
);
if(Auth::attempt($user_data))
{
return redirect('');
}
else
{
return back()->with('error', 'you typed wrong data');
}
}
login page
#extends('layout')
#section('content')
<div class="container2">
<div class="container">
<div class="card card-container">
<h1 style="text-align: center;">Admin login</h1>
#if(isset(Auth::user()->email))
<script>window.location="/main/successlogin";</script>
#endif
#if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ url('/main/checklogin') }}">
{{ csrf_field() }}
<div class="form-group">
<label>Unesi email</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label>Unesi šifru</label>
<input type="password" name="password" class="form-control" />
</div>
<div class="form-group">
<input type="submit" name="login" class="btn btn-primary" value="Login" />
</div>
</form>
</div><!-- /card-container -->
</div><!-- /container -->
</div><!-- /container -->
#endsection
Routes
Route::get('/', 'MainController#successlogin')->name('main');
Route::get('/admin', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/logout', 'MainController#logout');
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'lastname', 'level',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Try this:
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data = array(
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
);
if(Auth::attempt($user_data))
{
return redirect('');
}
else
{
return back()->with('error', 'you typed wrong data');
}
}
In laravel i am making an application that uploads a file and the user can download that same file.
But each time i click to upload i get this error.
FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
my view code is this:
#extends('layouts.app')
#section('content')
#inject('Kala','App\Kala')
<div class="container">
<div class="row">
#include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
#endsection
and my controller
public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
and i change the upload max size in php.ini to 1000M.
plz help
im confusing
I'll recommend you using filesystems for that by default the folder is storage/app you need to get file from there
if your file is located somewhere else you can make your own disk in config/filesystems e.g. 'myDisk' => [
'driver' => 'local',
'root' =>base_path('xyzFolder'),
],
and you can call it like
use Illuminate\Support\Facades\Storage;
$data = Storage::disk('myDisk')->get('myFile.txt');
this is obviously to get file and you can perform any other function by following laravel docs.