Creating default object from empty value on update Laravel - php

I realize this question has been asked several times on this forum, but none of the solutions given has resolved my particular issue.
I get the above error when trying to update my DB.
Here is a snippet of my code
I have tried adding findorfail on my request by id
$service=Service::findorfail($request->input('id'));
This returns a 404 page.
ServiceController.php
public function updateService(Request $request){
// return $request->all();
$this->validate($request, ['serviceTitle'=> 'required',
'serviceSubTitle'=> 'required',
'description'=> 'required',
'slug' => 'required|min:3|max:255|unique:services',
'serviceImage'=>'image|nullable|max:1999']);
$service=Service::find($request->input('id'));
$service->title =$request->input('serviceTitle');
$service->sub_title =$request->input('serviceSubTitle');
$service->slug =$request->input('slug');
$service->description =$request->input('description');
if($request->hasFile('serviceImage')) {
//1 : get filename with ext
$fileNameWithExt = $request->file('serviceImage')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('serviceImage')->getClientOriginalExtension();
//4: filename to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('serviceImage')->storeAs('public/serviceImage', $fileNameToStore);
$old_image =Service::find($request->input('id'));
if($old_image!='noimage.jpg') {
Storage::delete('public/serviceImage/'.$old_image->image);
}
$service->image =$fileNameToStore;
}
$service->update();
return redirect('/services')->with('status', 'The '.$service->title.' Service has been updated successfully');
}
The error log tells me the error is on this specific line:
$service->title =$request->input('serviceTitle');
Thank you for time and assistance.

Related

Laravel can't found a stored file 404 NOT FOUND

posting this again because I didn't find to solution yet.
Laravel can't found the file storage/app/public/upload
when I usehttp://127.0.0.1:8000/storage/upload/The_fileName.x I get 404 not found
I've tried http://127.0.0.1:8000/storage/app/public/upload/The_fileName.x too.
what should I do ?
In DocumentController :
public function store(Request $request)
{
$request->validate([
'doc' => "required",...
]);
$document = new document();
$file = $request->file('doc');
$filename=time().'.'.$file->getClientOriginalExtension() ;
// I've tried these too, one by one and still get the same error .
//$file_path = public_path('public/upload');
//$file->move($file_path, $filename);
//Storage::disk('local')->put($file, $filename);
//request('doc')->store('upload', 'public');
$file->storeAs('public/upload', $filename);
$document->doc = $request->input('doc', $filename);
$document->candidate_id = $candidate_id;
$document->save();
Thank you in advance
According to Laravel document File Storage, you need to create a symbolic link at public/storage which points to the storage/app/public then you can access the file with http://127.0.0.1:8000/upload/The_fileName.x.

Uploading image in 000webhost don't work using laravel framework

I'm working on a Laravel project, and I make a feature that the user can upload image for its profile, and I use the public path to save the avatars cause 000webhost doesn't support (storage:link) and every thing works better in local
but when I upload the project on 000webhost, it refuses to upload the image and returns error (The image failed to upload.)
How can i solve it
config/filesystem.php
'public' => [
'driver' => 'local',
'root' => public_path('storage2'),
'url' => env('APP_URL').'/storage2',
'visibility' => 'public',
],
controller
public function Change(Request $request)
{
$Validate = $this->Validation($request);
if (!$Validate->fails()) {
$User = $this->getUser();
$OldImage = $User->image;
$Extension = $request->file("image")->getClientOriginalExtension();
$NewImage = str_random(30) . "." . $Extension;
Storage::putFileAs($this->privatePath, $request->file("image"), $NewImage);
$User->update(["image" => $NewImage]);
Storage::delete($this->privatePath ."/". $OldImage);
session()->flash("message", "You have changed your image");
return back();
} else {
session()->flash("error", $Validate->errors()->first());
return back();
}
}
But the problem is not in the code, cause it works in local
I think the problem with some permissions or in file .htaccess or anything like that

I get a 404 error when he should not :laravel

I developed an API and I have a problem with this page I add it in my route and always I get a 404 error I don't know why
this my controller:
class InsertPPictureController extends Controller
{
public function profilepicture (Request $request)
{
$input = $request->all();
$validator = Validator::make($input, [
'id_user'=> 'required',
'picture'=> 'image|nullable|max:1999'
] );
$user = User::findOrFail($request->id);
$user_id = $request->id ;
if($request->hasFile('picture')){
// Get filename with the extension
$filenameWithExt = $request->file('picture')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('picture')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $user_id.'.'.$extension;
// Upload Image
$path = $request->file('picture')->storeAs('public/profilepic', $fileNameToStore);
$user->pic_path = $fileNameToStore ;
$user->update();
} else {
$fileNameToStore = 'noimage';
}
return response()->json(' Success : User updated with success ',200);
}
}
and this is my api.php
Route::group(['middleware' => ['jwt.verify']], function() {
Route::get('logout', 'AuthController#logout');
Route::post('postcreditscards', 'CreditsCardsController#stockcards');
Route::get('getcreditscards', 'CreditsCardsController#index');
Route::get('getmybalance', 'MyBalanceController#index');
Route::get('getuserdata', 'AuthController#getuser');
Route::post('sendMoneyTransaction', 'MyBalanceController#updatebalance');
Route::post('isvalidnumber', 'AuthController#validnumber');
Route::post('updateuser', 'AuthController#updateuser');
Route::post('insertprofilepicture','InsertPPictureController#profilepicture');
});
all the pages work fine only this page doesn't work
Route::post('insertprofilepicture','InsertPPictureController#profilepicture');
You are getting 404 error because of the following line in you controller code:
$user = User::findOrFail($request->id);
The id you are providing, does not exist in your users table and as you are not catching the exception hence Laravel is returning a 404 response, which is actually ModelNotFoundException
Reference here
Go to : "Not Found Exceptions" section of the above link. Here is some lines from doc:
If the exception is not caught, a 404 HTTP response is automatically sent back to the user
echo '<pre>'.print_r($user,1);die();
just put in this line after the
$user = User::findOrFail($request->id);
line. i suggest you to check the data array pass to this controller. if it is pass, after line by line you can check.

Laravel get path of saved file from upload

I have a laravel upload for file (along with other data that is passed to the database) Everything works. But I just can't figure out how to save the path of the file that is saved.
Here is my controller function:
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'logo' => 'nullable',
'original_filename' => 'nullable',
]);
//This is where the file uploads?
if ($request->hasFile('logo')) {
$request->file('logo')->store('carrier_logo');
$request->merge([
'logo' => '',//TODO: get file location
'original_filename' => $request->file('logo')->getClientOriginalName(),
]);
}
Carrier::create($request->all());
return redirect()->route('carriers.index')->with('toast', 'Carrier created successfully.');
}
The thing I want to achieve:
I want logo to fill with something like carrier_logo/ZbCG0lnDkUiN690KEFpLrNcn2exPTB8mUdFDwAKN.png
The thing that happened every time I tried to fix it was that it placed the temp path in the database. Which ended up being something in the PHP install directory.
Just assign result to variable:
$path = $request->file('logo')->store('carrier_logo');
According to docs
Then you can do with $path variable whatever you want.
just assign the value like this.
$location=base_path('img/'.$filename);
and save it in db.
You could do this:
For FileName
$fileName = $request->file('test')->getClientOriginalName();
OR
$fileName = $request->user()->id.'.'.$request->file('logo')->getClientOriginalExtension();
$imageDirectory = 'logo_images';
$path = $request->file('logo')->storeAs($imageDirectory, $fileName);
dd($path);

Laravel 5 form validation on failure keep uploaded data

I am working on a Laravel project and I have routes set up for a form page where it shows the form on GET and it analyzes it on POST:
Route::get('/update-data', [
'as' => 'user.settings.edit-data',
'uses' => 'UserController#editData',
]);
Route::post('/update-data', [
'as' => 'user.settings.update-data',
'uses' => 'UserController#updateData',
]);
In this form I ask the user to fill out two fields with text and I also ask them to upload two files. Both files must be jpeg, png or pdf. In the controller I have:
$this->validate($request,
[
'phone' => 'required',
'email' => 'required|email',
'file1' => 'required|mimes:jpeg,png,pdf',
'file2' => 'required|mimes:jpeg,png,pdf',
]);
If that succeeds, then the code will continue executing and save everything, but if not it will redirect the user back to the form. Is there a way to still have the file chosen so that the user doesn't need to look for it again?
I would suggest validating using server side code (not javascript, although both can be nice from the user perspective (but obviously don't rely on the js validation).
I usually validate like this in Laravel (I'm not the biggest fan of their built in validator). Then after the validation you can use Laravel's File class to get the file name and re-post the data to the view:
$file = Request::file('file1');
$accepts = ['jpeg', 'png', 'pdf'];
$ext = $file->getClientOriginalExtension();
$filename = $file->getClientOriginalName();
if( !in_array($ext, $accepts) )
{
return view('your-view')->withErrors('Invalid File Format');
}
else
{
//File has one of the correct extensions,
//return the filename to the view so it can be
//re-displayed in the input
return view('your-view', ['filename' => $filename]);
}
Or if you prefer the non-facade way:
$file = $request->file('file1');
$accepts = ['jpeg', 'png', 'pdf'];
$ext = $file->getClientOriginalExtension();
$filename = $file->getClientOriginalName();
if( !in_array($ext, $accepts) )
{
return view('your-view')->withErrors('Invalid File Format');
}
else
{
//File has one of the correct extensions,
//return the filename to the view so it can be
//re-displayed in the input
return view('your-view', ['filename' => $filename]);
}
This takes advantage of Laravels File class.

Categories