Laravel File Upload Validation - php

I'm new to Laravel. I have a form with a File upload function on it. How can I validate their file? I will only allowed Microsoft Word files. Here's my validation code.
I just want check if they insert a ms word file and if not it will not be processed.
public function store()
{
// Validate
$rules = array(
'pda' => 'required|unique:forms',
'controlnum' => 'required|unique:forms',
'date' => 'required',
'churchname' => 'required',
'title' => 'required',
'pastorname' => 'required',
'contactnum' => 'required',
'address' => 'required',
'state' => 'required',
'region' => 'required',
'area' => 'required',
'city' => 'required',
'zipcode' => 'required|numeric|max:9999',
'tgjteachertraining' => 'required',
'localcontact' => 'required',
'tgjdatestart' => 'required',
'tgjdateend' => 'required',
'tgjcourse' => 'required|numeric',
'childrengraduated' => 'required|numeric|max:450',
'childrenacceptjesus' => 'required|numeric',
'howmanycomitted' => 'required|numeric',
'recievedbibles' => 'required|numeric',
'descgradevent' => 'required',
'whatwillyoudo' => 'required',
'pastortest' => 'required',
'teachertest' => 'required',
'childrentest' => 'required',
'file' => 'required|max:10000',
);
$validator = Validator::make(Input::all(), $rules);
// process the form
if ($validator->fails()) {
return Redirect::to('forms/create')->withErrors($validator);
} else {
// store
$forms = new Forms;
$forms->pda = Input::get('pda');
$forms->controlnum = Input::get('controlnum');
$forms->date = Input::get('date');
$forms->churchname = ucwords(Input::get('churchname'));
$forms->title = ucwords(Input::get('title'));
$forms->pastorname = ucwords(Input::get('pastorname'));
$forms->address = Input::get('address');
$forms->contactnum = Input::get('contactnum');
$forms->state = Input::get('state2');
$forms->region = Input::get('region2');
$forms->area = Input::get('area2');
$forms->citytown = Input::get('city2');
$forms->zipcode = Input::get('zipcode');
$forms->tgjteachertraining = Input::get('tgjteachertraining');
$forms->localcontact = ucwords(Input::get('localcontact'));
$forms->tgjdatestart = Input::get('tgjdatestart');
$forms->tgjdateend = Input::get('tgjdateend');
$forms->tgjcourse = Input::get('tgjcourse');
$forms->childrengraduated = Input::get('childrengraduated');
$forms->childrenacceptjesus = Input::get('childrenacceptjesus');
$forms->howmanycomitted = Input::get('howmanycomitted');
$forms->recievedbibles = Input::get('recievedbibles');
$forms->descgradevent = Input::get('descgradevent');
$forms->whatwillyoudo = Input::get('whatwillyoudo');
$forms->pastortest = Input::get('pastortest');
$forms->teachertest = Input::get('teachertest');
$forms->childrentest = Input::get('childrentest');
$file = Input::file('file');
$filename = $file->getClientOriginalName();
$destinationPath = 'uploads/'.Input::get('pda');
$uploadSuccess = Input::file('file')->move($destinationPath, $filename);
$forms->docurl = 'uploads/'.Input::get('pda').'/'.$filename;
if( $uploadSuccess ) {
$forms->save();
//Session::flash('message', 'Successfully submitted form!');
return Redirect::to('forms/create');
Session::flash('message', 'Successfully submitted form!');
}
else {
return Response::json('error', 400);
}
}
}

To validate mime type of a file input in Laravel you can use the mimes rule. Remember to match the mime type detected with the actual mime of file you provide. It may vary on different servers.
For example, you want to enable adding and word document in you form:
1) in config/mimes.php add the below mime types:
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
2) in your validation $rules add the following elements:
'file' => 'required|max:10000|mimes:doc,docx' //a required, max 10000kb, doc or docx file

Try this?
'file' => 'required|max:10000|mimes:application/vnd.openxmlformats-officedocument.wordprocessingml.document'
You may want to set some custom message for the response though :)

As of Laravel 9.22 you can write the validation rules a lot shorter and more readable like:
'file' => ['required', File::types(['doc', 'docx'])->smallerThan(10000)]
You can find the available methods in this pr: https://github.com/laravel/framework/pull/43271

Related

How to save easily all request data after validation in laravel, See my code please

My Controller:
public function chamberProcess(Request $request){
$this->validate($request, [
'hospital_name' => 'required',
'start_time' => 'required',
'end_time' => 'required',
'start_day' => 'required',
'end_day' => 'required',
'address' => 'required',
'limit' => 'required'
]);
$chamberinfo = new DoctorChamber;
$chamberinfo->hospital_name = $request->hospital_name;
$chamberinfo->start_time = $request->start_time;
$chamberinfo->end_time = $request->end_time;
$chamberinfo->start_day = $request->start_day;
$chamberinfo->end_day = $request->end_day;
$chamberinfo->address = $request->address;
$chamberinfo->limit = $request->limit;
$chamberinfo->save();
return redirect(route('viewchamber'));
}
I don't want to write the bellow codes:
$chamberinfo->hospital_name = $request->hospital_name;
$chamberinfo->start_time = $request->start_time;
$chamberinfo->end_time = $request->end_time;
$chamberinfo->start_day = $request->start_day;
$chamberinfo->end_day = $request->end_day;
$chamberinfo->address = $request->address;
$chamberinfo->limit = $request->limit;
It works fine but I want $request all or something like this. When I add 100 data then should I write 100 line of avobe code? Ofcourse there is solution but I don't know. Please help me!
$chamberinfo = DoctorChamber::create($request->validated());
You can use:
DoctorChamber::create($request->all());

Command (Store) is not available for driver (Gd) using laravel 6

I want to add a user (name, email, image, multiple images ...), and I tried to resize the image and multiple images for upload very quickly we use package intervention, I execute cmd php composer require intervention/image, i added Intervention\Image\ImageServiceProvider::class and Image'=>Intervention\Image\Facades\Image::class in config/app.php, I also added use Intervention\Image\Exception\NotReadableException; and use Intervention\Image\Facades\Image; in RegisterController.php.
but its give me error Command (Store) is not available for driver (Gd)
but its give me error Command (Store) is not available for driver (Gd)
D:\wamp\www\aswaktin\vendor\intervention\image\src\Intervention\Image\AbstractDriver.php:119
RegisterController.php
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['bail','required', 'string','min:3', 'max:50','regex:/^[\pL\s\-]+$/u'],
'email' => ['bail','required', 'string', 'email', 'max:255', 'unique:users'],
'telephone'=> ['bail','required','regex:/^06\d{8}$/','unique:users'],
'password' => ['bail','required', 'string', 'min:8', 'confirmed'],
'adressem' => ['bail','required', 'string', 'min:13','max:255'],
'adressem' => ['bail','required', 'string', 'min:13','max:255'],
'adresser' => ['bail','required', 'string', 'min:13','max:255'],
'image' => ['bail','required','mimes:jpeg,jpg,png,gif,svg','max:2048'],
'images.*' => ['bail','required','mimes:jpeg,jpg,png,gif,svg','max:2048']
]);
}
protected function create(array $data)
{
//image
$user = new User();
//$jdate = Carbon::now();
$request = app('request');
if($request->hasFile('image'))
{
$image = $request->file('image');
$url = Storage::put("user/" , $image->getClientOriginalName());
$image = Image::make($image);
$image->resize(250,125);
$path = $request->image->store('profiles');
$user->image = $path;
}
$im = $user->image;
//images
$dataim = array();
if($request->hasFile('images'))
{
foreach($request->images as $file)
{
$file = Image::make($file);
$file->resize(250,125);
$path = $file->store('profiles');
array_push($dataim,$path);
}
}
$user->images=json_encode($dataim);
$imm =$user->images;
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'telephone' => $data['telephone'],
'country_id' => $data['country_id'],
'state_id' => $data['state_id'],
'autrei' => $data['autrei'] ?? null,
'city_id' => $data['city_id'],
'autreh' => $data['autreh'] ?? null,
'adressem' => $data['adressem'],
'adresser' => $data['adresser'],
'image' => $im,
'images' => $imm
]);
}
The problem is, you’re overwriting the uploaded file instance ($file) with an Intervention instance, but then trying to call store (and UploadedFile method) on that Intervention image instance. You’ll need to use a different variable name for your Intervention image instance instance.

i am trying to save the image using the `Intervention \ Image library`. and I found an error Image source is not readable

public function store(Request $request)
{
$this->validate($request, [
'judul' => 'required',
'category_id' => 'required',
'konten' => 'required',
'gambar' => 'required',
]);
$gambar = $request->gambar;
$new_gambar = time().$gambar->getClientOriginalName();
$post = Posts::create([
'judul' => $request->judul,
'category_id' => $request->category_id,
'konten' => $request->konten,
'gambar' => 'public/uploads/posts/'.$new_gambar,
'slug' => Str::slug($request->judul),
'users_id' => Auth::id()
]);
$img = Image::make('public/uploads/',$gambar->getRealPath())->resize(300,
300)->save('public/uploads/', $gambar->getClientOriginalName());
$gambar->move('uploads', $new_gambar);
$post->tags()->attach($request->tags);
return redirect('post');
}
Add enctype in your html form
enctype="multipart/form-data"
And change for this in your controller:
$img = Image::make($request->file('gambar')->getRealPath());
Also check permissions of the directory in which you are uploading the file
make sure form has enctype:
<form class="form" ... enctype="multipart/form-data">
change controller
use Intervention\Image\ImageManagerStatic as Image;
public function store(Request $request)
{
$this->validate($request, [
// 'judul' => 'required',
//if judul column type is varchar need to set max varchar value or less
//varchar max 255, if higer than 255 strings, extra string will be truncated
'judul' => 'required|string|max:200',
// 'category_id' => 'required',
//category should exist
'category_id' => 'required|exists:categories,id',
'konten' => 'required',
// 'gambar' => 'required',
//validating image is successfully uploaded and is image format
'gambar' => 'required|file|image|mimes:jpg,jpeg,png',
//validation for tags, assuming 1 input <select name="tags[]" multiple="multiple"/>
'tags' => 'array',
'tags.*' => 'exists:tags,id'//each value of input select exists in tags table
]);
// $gambar = $request->gambar;
//get the file from <input type="file" name="gambar"/>
$gambar = $request->file('gambar');
$new_gambar = time().$gambar->getClientOriginalName();
//make path to save image: sample public path
$file_path = public_path("uploads/post/{$new_gambar}");
$img = Image::make($gambar)
->resize(300,300)
->save($file_path);
$post = Posts::create([
'judul' => $request->judul,
'category_id' => $request->category_id,
'konten' => $request->konten,
// 'gambar' => 'public/uploads/posts/'.$new_gambar,
//should maake the image first
'gambar' => $file_path,
'slug' => Str::slug($request->judul),
'users_id' => Auth::id() // <- if it is to get current logged in user, use Auth::user()->id
]);
// $gambar->move('uploads', $new_gambar); //let Intervention do this for you
// $post->tags()->attach($request->tags);
//if tags exists (get values frominput select)
$post->tags()->sync($request->input('tags', []));
//$request->input('tags', []) <- if input tags is not null get value, else use empty array
//if route have name e.g Route::get('post', 'PostController#post')->name('post');
//return redirect()->route('post');
return redirect('post');
}

method not allowed laravel validation post

I want to validate input in POST method but the result message shows that Method is Not Allowed. Here's my code for create new user in database (UserController.php)
public function userRegister(Request $request)
{
$data['error']['state'] = false;
$rules = [
'name' => 'required',
'username' => 'required|unique:username',
'nip' => 'required|unique:nip',
'email' => 'required|unique:email',
'phone' => 'required',
'avatar' => 'required',
'password' => 'required',
'faculty_id' => 'required',
'building_id' => 'required',
'room_id' => 'required'
];
$message = [
'required' => 'Fill the required field.',
'username.unique' => 'Username already taken.',
'nip.unique' => 'Staff ID already taken.',
'email.unique' => 'Email already taken.',
];
$validator = $this->validate($request,$rules,$message);
if($validator->fails()){
$data['error']['state'] = true;
$data['error']['data'] = $validator->errors()->first();
}
else{
$data['user']['name'] = $request->input('user.name');
$data['user']['surname'] = $request->input('user.surname');
$data['user']['username'] = $request->input('user.username');
$data['user']['nip'] = $request->input('user.nip');
$data['user']['email'] = $request->input('user.email');
$data['user']['password'] = Hash::make($request->input('user.password'));
$data['user']['phone'] = $request->input('user.phone');
$data['user']['level'] = $request->input('user.role');
$data['user']['username_telegram'] = $request->input('user.username_telegram');
$data['user']['user_email_action'] = $request->input('user.user_email_action');
$data['user']['user_telegram_action'] = $request->input('user.user_telegram_action');
$data['user']['faculty_id'] = $request->input('user.faculty');
$data['user']['building_id'] = $request->input('user.building');
$data['user']['room_id'] = $request->input('user.room');
$data['user']['verified'] = 0;
if(!empty($request->input('user.avatar'))){
$data['user']['avatar'] = $request->input('user.username').'-'.$request->input('user.new_avatar');
}
else{
$data['user']['avatar'] = 'default.png';
}
$user_id = DB::table('register')->insertGetId($data['user'],'id');
}
return response()->json($data);
}
Here's the message:
Error Message
Do you know how to solve it? Thank you.
Your question doesn't show the routes of your application but you'll need to make sure your form is set to post
<form action="/my/url/path" method="post">
and your route is set to 'post'
E.g.
Route::post('/my/url/path', 'MyController#userRegister');
Please note that if you're not using Laravel Collective you'll need to make sure you include the CSRF token
<form method="POST" action="/my/url/path">
#csrf (laravel 5.6)
{{ csrf_field() }} (previous versions)

Laravel image being posted to database as "/private/var/tmp/"

I'm trying to store an image in my Laravel project, but I'm having an issue. The image is sucessfuly being added to the /public/images folder as its filename, but when the request hits the database, its added as /private/var/tmp/XXXXX. I've tried to set $request->file as the name, but it still posts as the var/temp.
Controller
public function store(Request $request)
{
$rules = [
// 'address' => 'required',
// 'city' => 'required',
// 'postcode' => 'required',
// 'restDesc' => 'required',
// 'telNumb' => 'required',
// 'resWebsite' => 'required',
// 'restDesc' => 'required',
// 'business_id' => 'unique:busprofiles,business_id',
];
$customMessages = ["Message"];
if ($request->hasFile('file')) {
$request->file->store('public/uploads');
$filename = $request->file->getClientOriginalName();
$filesize = $request->file->getClientSize();
$request->file = $request->file->storeAs('public/uploads', $filename);
}
$this->validate($request, $rules, $customMessages);
Busprofile::create($request->all());
return redirect()->route('business.dashboard')
->with('success', 'Profile created successfully');
}
If it helps: return $request->file returns the correct URL.
The problem is in Busprofile::create($request->all());. You do indeed get the original filename with $filename = $request->file->getClientOriginalName(); but your request stays the same.
Create the array for the database entries manually, according to your database needs.
$data = ['filename' => $request->file->getClientOriginalName(),
...,
];
and
Busprofile::create($data);

Categories