Seeking to understand how this error "Illuminate\Http\Exceptions\PostTooLargeException" comes about - laravel

I've got the following code and it's working just well as expected when uploading images but I noticed when I try to upload a video I get the error Illuminate\Http\Exceptions\PostTooLargeException. I was expecting to get an error on browser "The make field should be an image" just as the other validations are working. Could someone kindly explain what's happening here, shouldn't validation stop immediately the uploaded file is found to be not an image? Is the validation checking for size first and yet that's not what I've provided in validation?
public function store(Request $request)
{
$this->validate($request, [
'condition' => 'required',
'make' => 'required | alpha',
'model' => 'required | alpha_dash',
'filenames' => 'required | image',
'filenames.*' => 'image',
]);
$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;
}
}
$vehicle = new Vehicle;
$vehicle->condition = $request->condition;
$vehicle->make = $request->make;
$vehicle->model = $request->model;
$vehicle->filenames= $files;
$vehicle->save();
return redirect(route('vehicles.create'))->with('flash', 'Vehicle Post Created
Successfully');}

Related

Laravel validator does'nt correctly validate file mime type

I send multiple files to my server with postman
And these files are uploaded correctly but they are not properly validated before uploading
this is my controller
public function store(Request $request)
{
// دریافت دایرکتوری مطالبه مربوطه : $demand=Demand::find(72)->files->first()->file_directoryس
//{"title":"this is test title","demandContent":"this is test content "} send as form-data request
//------------------------------------------- Valid Uploaded File ---------------------------------
$rules = array(
'file' => 'required',
'file.' => 'mimes:doc,pdf,docx,zip,jpg,jpeg,rar'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
return response()->json(['errors' => $error->errors()->all()]);
//-------------------------------------------- Valid Uploaded File -------------------------------
$request->data=json_decode($request->data); //دریافت به صورت جیسون و تبدیل به شی
$demand=new Demand(['title' => $request->data->title,'content'=>$request->data->demandContent,'user_id'=>auth('api')->user()->id]);
if($demand->save()) //اگر درخواست در دیتابیس قبت شد
{
//----------------------------File Upload Scope---------------------------------------
if($request->hasfile('file'))
{
$path='public/demands/'.$demand->id.'/files';
foreach($request->file('file') as $file)
{
$filename=$file->getClientOriginalName();
$file->move($path, $filename);
}
$demand->files()->save(new File(['file_directory'=>$path]));
}
//----------------------------File Upload Scope---------------------------------------
return response()->json(['demand'=>new DemandResource($demand)],200);
}
return response()->json(['state'=>'false']);
}
In your validation rules you have forgotten * like:
$rules = [
'file' => 'required',
'file.*' => 'required|file|mimes:doc,pdf,docx,zip,jpg,jpeg,rar',
];

in laravel if condition not working in controller

i am trying to use if condition in controller ( IF IMAGE NOT UPLOADED it go to ELSE condition Or else go to IF ) but it was not working , it just redirecting registration from page when submitting a form
code
public function Enrollment(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'father_name' => 'required|string|max:225',
'address' => 'required|string|max:255',
'card_id' => 'required|string|max:255',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if ($request->image != '')
{
$input['name'] = strtoupper ($request['name']);
$input['father_name'] = strtoupper ($request['father_name']);
$input['address'] = strtoupper ($request['address']);
$input['card_id'] = strtoupper ($request['card_id']);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
$folder1 = public_path('IMAGE/');
$path1 = $folder1 . $input['image']; // path 1
$request->image->move($folder1, $input['image']); // image saved in first folder
$path2 = public_path('IMAGE/BACKUP_IMAGE/') . $input['image']; // path 2
\File::copy($path1, $path2);
}else{
$input['name'] = strtoupper ($request['name']);
$input['father_name'] = strtoupper ($request['father_name']);
$input['address'] = strtoupper ($request['address']);
$input['card_id'] = strtoupper ($request['card_id']);
}
Card::create($input);
return back()->with('success','Enrolled Successfully.');
}
try this
if($request->hasfile('user_image'))
Nice that you use laravel. At first I will give you some hints to improve your code snippet.
You've written
it just redirecting registration from page when submitting a form
that's correct, because if you submit the form without an image, the validation will say "false".
You can't check an required in this way:
if ($request->image != '') {
because it's required.
Actually your code skips the validation at all, it would be better if you use the following:
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'father_name' => 'required|string|max:225',
'address' => 'required|string|max:255',
'card_id' => 'required|string|max:255',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
If you dump your dd($validator); you will see all opertunities to validate the $request. Your errors you will find here: $validator->errors().
If something went wrong you should redirect back with the
->withInput()
so all data will stay in the form. Also possible with some explanation for the user ->withErrors():
// message information for the user
$messages = $validator->errors();
$messages->add('Your explanation');
// redirect
return redirect()->route('index')->withErrors($messages)->withInput();
Actually I am unsure why you save all $request in $input.
You can check https://laravel.com/docs/5.8/validation#using-rule-objects that for find an great solution for the strtoupper() usement.
Helpful links:
https://laravel.com/docs/5.8/validation
https://laravel.com/docs/5.8/session#flash-data

How to image upload into databae using laravel?

I am trying to upload an image into the database but unfortunately not inserting an image into the database how to fix it, please help me thanks.
database table
https://ibb.co/3sT7C2N
controller
public function Add_slider(Request $request)
{
$this->validate($request, [
'select_image' => 'required'
]);
$content = new Sliders;
if($request->file('select_image')) {
$content->slider_image = Storage::disk('')->putFile('slider', $request->select_image);
}
$check = Sliders::create(
$request->only(['slider_image' => $content])
);
return back()
->with('success', 'Image Uploaded Successfully')
->with('path', $check);
}
You should do with the following way:
public function Add_slider(Request $request)
{
$this->validate($request, [
'select_image' => 'required'
]);
$image = $request->file('select_image');
$extension = $image->getClientOriginalExtension();
Storage::disk('public')->put($image->getFilename().'.'.$extension, File::get($image));
$content = new Sliders;
if($request->file('select_image'))
{
$content->slider_image = $image->getFilename().'.'.$extension;;
$content->save();
$check = Sliders::where('id', $content->id)->select('slider_image')->get();
return back()->with('success', 'Image Uploaded Successfully')->with('path',$check);
}
}
And in view blade file:
<img src="{{url($path[0]->slider_image)}}" alt="{{$path[0]->slider_image}}">
This returns only the filename:
Storage::disk('')->putFile('slider', $request->select_image);
Use this instead:
Sliders::create([
'slider_image' => $request->file('select_image')->get(),
]);
Make sure the column type from database is binary/blob.

Method not allowed exception while updating a record

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpExceptionNomessage
I'm getting this error while trying to update a record in the database. Don't know what's the problem. This question might be a duplicate but I've checked all and couldn't find the answer. Please Help me with this.
Controller Update Method:
public function updateEvent(Request $request, $id=''){
$name = $request->name;
$startdate = date_create($request->start_date);
$start_date = $startdate;
$time = $request->start_time;
$start_time = $time;//date("G:i", strtotime($time));
$endDate = date_create($request->end_date);
$end_date =$endDate;
$time_e = $request->end_time;
$end_time = $time_e;//date("G:i", strtotime($time_e));
$location = $request->location;
$description = $request->description;
$calendar_type = $request->calendar_type;
$timezone = $request->timezone;
if ($request->has('isFullDay')) {
$isFullDay = 1;
}else{
$isFullDay = 0;
}
DB::table('events')->where('id', $id)->update(
array(
'name' => $name,
'start_date' => $start_date,
'end_date' => $end_date,
'start_time' => $start_time,
'end_time' => $end_time,
'isFullDay' =>$isFullDay,
'description' => $description,
'calendar_type' => $calendar_type,
'timezone' => $timezone,
'location' => $location,
));
// Event Created and saved to the database
//now we will fetch this events id and store its reminder(if set) to the event_reminder table.
if(!empty($id))
{
if (!empty($request->reminder_type && $request->reminder_number && $request->reminder_duration)) {
DB::table('event_reminders')->where('id', $id)->update([
'event_id' => $id,
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
}
else{
DB::table('event_reminders')->insert([
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
return redirect()->back();
}
Route:
Route::post('/event/update/{id}', 'EventTasksController#updateEvent');
Form attributes :
<form action="/event/update/{{$event->id}}" method="POST">
{{ method_field('PATCH')}}
i'm calling the same update function inside my calendar page and it working fine there. Don't know why it doesn't work here.
Check the routeing method.
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
patch should be the method called on route facade.
Change your route to patch:
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
For your comment:
You can send the method to the ajax call by something like data-method attribute on the element you click on,take the method and use it in your ajax call. see this question/answer for help. How to get the data-id attribute?

Update profile function

I have a function that check updates the users profile info. Currently, if I put |unique:users in the validator every time I try to update the profile info on the form it will not let me because a user (which is me) has my email. So I figured out the unique means that nobody, including the current user can have the email that is being updated.
So I need to compare the current auth email to the one in the database. If it matches then it is ok to update the profile info. I know this is simple but I am not sure how to implement it and if that is the right logic.
So where in this code would I post if (Auth::user()->email == $email){..update email...} http://laravel.io/bin/GylBV#6 Also, is that the right way to do this?
public function editProfileFormSubmit()
{
$msg = 'Successfully Updated';
$user_id = Auth::id();
$user = User::find($user_id);
$first_name = Input::get('first_name');
$last_name = Input::get('last_name');
$email = Input::get('email');
$phone_number = Input::get('phone_number');
$validator = Validator::make(Input::all(), array(
'email' => 'required|email',
'first_name' => 'required',
'last_name' => 'required',
'phone_number' => 'required'
));
if ($validator->fails()) {
return Redirect::route('edit-profile')
->withErrors($validator)
->withInput();
}else{
if(Input::hasFile('picture')){
$picture = Input::file('picture');
$type = $picture->getClientMimeType();
$full_image = Auth::id().'.'.$picture->getClientOriginalExtension();
if($type == 'image/png' || $type == 'image/jpg' || $type == 'image/jpeg'){
$upload_success = $picture->move(base_path().'/images/persons/',
$full_image);
if($upload_success) {
$user->picture = $full_image;
} else {
$msg = 'Failed to upload picture.';
}
}else{
$msg = 'Incorrect image format.';
}
}
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email = $email;
$user->phone_number = $phone_number;
$user->save();
return Redirect::route('invite')->with('global', $msg);
}
}
Worry not, Laravel has already considered this potential issue! If you take a look at the docs for the unique validation rule you'll see that it can take some extra parameters. As it happens, you can give it an id to ignore when looking at the unique constraint. So what you need to do is work out the id for the current model to update and pass that in. In the case of updating a logged-in user's profile it's made easy by Auth::id() as you already have in your code.
$rules = [
'email' => ['required', 'email', 'unique:users,email,'.Auth::id()],
'first_name' => ['required'],
// etc...
];
Obviously I chose to use the array syntax for validation rules there, but you can do the same with the pip syntax too. In a less specific system (create-or-add in a crud postSave type action) you can still do it by simply dong something like $model = Post::find($id) and then if $model is null you're creating and you just use 'unique' whereas if $model is not null, use 'unique:table,field,'.$model->getKey().

Resources