Creating default object from empty value in Laravel 8 - laravel

For some reason, I still get a warning message: Creating default object from empty value.
Product controller
public function update(Request $request, $id)
{
$products = new Product();
$products = Product::find($id);
if ($request->hasFile('image'))
{
$path = 'assets/uploads/products/'.$products->image;
if (File::exists($path))
{
File::delete($path);
}
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = time().'.'.$ext;
$file->move('assets/uploads/products/',$filename);
$products->image = $filename;
}
$products->name = $request->input('name');
$products->slug = $request->input('slug');
$products->small_description = $request->input('small_description');
$products->description = $request->input('description');
$products->origanl_price = $request->input('origanl_price');
$products->selling_price = $request->input('selling_price');
$products->qty = $request->input('qty');
$products->tax = $request->input('tax');
$products->status = $request->input('status') == TRUE? '1':'0';
$products->trending = $request->input('trending') == TRUE? '1':'0';
$products->meta_title = $request->input('meta_title');
$products->meta_keywords = $request->input('meta_keywords');
$products->meta_description = $request->input('meta_description');
$products->update();
return redirect('/products')
->with('success', 'Product updated Successfully');
}
When I update the product, the page returns an error.
Creating default object from empty value.
How can I properly initialize the new empty object?

Related

Requesting solution for laravel 8 project

I'm an elementary web developer, I'm facing a problem. Please help me solve this. I'm creating both row and column dynamic. for save() is fine. But for update, only name is updated and other item
quantities cannot. Here is my codes.
//for save()
public function stockAdd(Request $request)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$user_id = Auth::user()->user_id;
$stock_id = random_int(100000, 999999);
$stocks = new Stocks();
$stocks->stock_id = $stock_id;
$stocks->owner_id = $user_id;
$stocks->stock_name = request()->stock_name;
$stocks->my_stock = 0;
$stocks->disable = 0;
$stocks->save();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
$stockitems = new StockItems();
$stockitems->stock_id = $stock_id;
$stockitems->product_id = $product->product_id;
$stockitems->owner_id = $user_id;
if(request()->$product_id > 0){
$stockitems->count = request()->$product_id;
}else{
$stockitems->count = 0;
}
$stockitems->save();
}
}
}
return redirect()->back()->with('successAddMsg','Successfully Added');
}
//for update()
public function stockUpdate(Request $request, $id)
{
$validator = validator(request()->all(), ['stock_name' => 'required']);
if($validator->fails()) {
return back()->withErrors($validator);
}
$stock = Stocks::findOrFail($id);
$stock->stock_name = request()->stock_name;
$stock->my_stock = 0;
$stock->disable = 0;
$stock->update();
$brands = Brands::all();
$products = Products::all();
foreach ($brands as $brand){
foreach ($products as $product){
if($product['brand_id'] == $brand['id']){
$product_id = $product->product_id;
//dd($product_id);
$stockitemitems = DB::table("stock_items")->select("*")->where("owner_id",Auth::user()->user_id)->where("stock_id",$stock->stock_id)->get();
$stockitems->count = $request->input($product_id);
$stockitems->update();
}
}
}
return redirect(route('user.stock-list'))->with('successAddMsg','Successfully Added');
}
The problem shows like this "Creating default object from empty value"

Why foreach loop is not working in same method in Laravel where if condition has file?

Why is the foreach loop not working in the same method in Laravel if the condition has a file? But when I remove the if condition, then the foreach is working. Otherwise, only the file is saved.
public function store(Request $request)
{
$userBasic = new UserBasic();
$userBasic->userId = $request->userId;
$userBasic->phone = $request->phone;
$userBasic->fullName = $request->fullName;
$userBasic->dob = $request->dob;
$userBasic->country = $request->country;
if ($request->hasFile('profileImg')) {
$img = $request->file('profileImg');
$imgName = time() . rand() . '.' . $img->extension();
$img->move(public_path('assets/img'), $imgName);
$profileImg = 'assets/img/' . $imgName;
$userBasic->profileImg = $profileImg;
}
$userBasic->status = $request->has('status');
$userBasic->save();
foreach ($request->medias as $media ) {
$userSml = new UserSocialMediaLink();
$userSml->userId = $request->userId;
$userSml->mediaName = $media['name'];
$userSml->mediaLink = $media['link'];
$userSml->save();
}
}

I get this error when trying to verify the email of candidates, Array to String conversion

I have a laravel system that when someone registers, they get a link on their emails where they have to click on it to verify their email. Once they click the link, their information is stored in the users table and the candidates table.
However, values are only inserted in the users table and not the candidates table, and I get the error "Array to string conversion".
Also, the link works well in local host but not after hosting the system.
RegisiterController.php
Str.php`
public function registerCandidate(Request $request){
if(setting('general_enable_candidate_registration')!=1){
return abort(401);
}
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'national_id'=>'required',
'gender'=>'required',
'email'=>'required|email|string|max:255|unique:users',
'date_of_birth_year'=>'required',
'date_of_birth_month'=>'required',
'date_of_birth_day'=>'required',
'categories'=>'required',
'picture' => 'nullable|max:'.config('app.upload_size').'|mimes:jpeg,png,gif',
'cv_path' => 'nullable|max:'.config('app.upload_size').'|mimes:'.config('app.upload_files'),
];
if(setting('general_candidate_captcha')==1){
$rules['captcha'] = 'required|captcha';
}
foreach(CandidateFieldGroup::where('registration',1)->orderBy('sort_order')->get() as $group){
foreach($group->candidateFields as $field){
if($field->type=='file'){
$required = '';
if($field->required==1){
$required = 'required|';
}
$rules['field_'.$field->id] = 'nullable|'.$required.'max:'.config('app.upload_size').'|mimes:'.config('app.upload_files');
}
elseif($field->required==1){
$rules['field_'.$field->id] = 'required';
}
}
}
$this->validate($request,$rules);
$requestData = $request->all();
$password= $request->password;
$requestData['name']= $request->first_name.' '.$request->last_name;
$requestData['display_name'] = $request->first_name;
$requestData['password'] = Hash::make($password);
$requestData['role_id'] = 3;
$fields = CandidateField::get();
//check if email verification is required
if(setting('general_candidate_verification')==1){
do{
$hash = Str::random(30);
}while(PendingUser::where('hash',$hash)->first());
$formData = $_POST;
$formData['name'] = $request->first_name.' '.$request->last_name;
$formData['display_name'] = $request->first_name;
$formData['role_id'] = 3;
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(PENDING_USER_FILES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$formData['picture'] = $file;
}
else{
$formData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = uniqid().'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$formData['cv_path'] = $file;
}
else{
$formData['cv_path'] =null;
}
$pendingUser = PendingUser::create([
'role_id'=>3,
'data'=> serialize($formData),
'hash'=> $hash
]);
//scan for files
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]) && $field->type=='file' && $request->hasFile('field_'.$field->id))
{
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
//dd($name);
$extension = $request->{'field_'.$field->id}->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $pendingUser->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$pendingUser->pendingUserFiles()->create([
'file_name'=>$_FILES['field_'.$field->id]['name'],
'file_path'=>$file,
'field_id'=>$field->id
]);
}
}
//send email to user
$link = route('confirm.candidate',['hash'=>$hash]);
$this->sendEmail($request->email,__('site.confirm-your-email'),__('site.confirm-email-mail',['link'=>$link]));
return redirect()->route('register.confirm');
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $request->date_of_birth_year.'-'.$request->date_of_birth_month.'-'.$request->date_of_birth_day;
$requestData['date_of_birth'] = $dateOfBirth;
//checkfor picture
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(CANDIDATES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$requestData['picture'] = $file;
}
else{
$requestData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$requestData['cv_path'] = $file;
}
else{
$requestData['cv_path'] =null;
}
$user->candidate()->create($requestData);
//save categories
$user->candidate->categories()->attach($request->categories);
//now save custom fields
$customValues = [];
//attach custom values
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]))
{
if($field->type=='file'){
if($request->hasFile('field_'.$field->id)){
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
$extension = $request->{'field_'.$field->id}->extension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$customValues[$field->id] = ['value'=>$file];
}
}
else{
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
}
$user->candidateFields()->sync($customValues);
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
public function confirmCandidate($hash){
//get pending user
$pendingUser = PendingUser::where('hash',$hash)->first();
if(!$pendingUser){
abort(404);
}
$requestData = unserialize($pendingUser->data);
$password = $requestData['password'];
$requestData['password'] = Hash::make($password);
//check for profile picture and move to new directory
if(!empty($requestData['picture']) && file_exists($requestData['picture'])){
$file = basename($requestData['picture']);
$newPath = UPLOAD_PATH.'/'.CANDIDATES.'/'.$file;
rename($requestData['picture'],$newPath);
$requestData['picture'] = $newPath;
}
if(!empty($requestData['cv_path']) && file_exists($requestData['cv_path'])){
$file = basename($requestData['cv_path']);
$newPath = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$file;
rename($requestData['cv_path'],$newPath);
$requestData['cv_path'] = $newPath;
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $requestData['date_of_birth_year'].'-'.$requestData['date_of_birth_month'].'-'.$requestData['date_of_birth_day'];
$requestData['date_of_birth'] = $dateOfBirth;
$user->candidate()->create($requestData);
//save categories
if(isset($requestData['categories'])){
$user->candidate->categories()->attach($requestData['categories']);
}
$fields = CandidateField::get();
$customValues = [];
//attach custom values
foreach($fields as $field){
if($field->type=='file'){
$pendingFile = $pendingUser->pendingUserFiles()->where('field_id',$field->id)->first();
if($pendingFile){
//generate name for file
$name = $pendingFile->file_name;
$info = new \SplFileInfo($name);
$extension = $info->getExtension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$file = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$name;
rename($pendingFile->file_path,$file);
$customValues[$field->id] = ['value'=>$file];
}
}
elseif(isset($requestData['field_'.$field->id])){
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
$user->candidateFields()->sync($customValues);
$pendingUser->delete();
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
`

Error Call to a member function getRealPath() on bool

I am get this error"Call to a member function getRealPath() on bool"
if($request->hasFile('content')) {
$filenameWithExt = $request->file('content')->getClientOriginalName();
$filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension = $request->file('content')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('content')->storeAs('public/content',$fileNameToStore);
} else {
$fileNameToStore = 'No Image,Music and Video selected please! check and try again.';
}
$post = new Post;
$post->body = $request->input('body');
$post->content = $fileNameToStore;
//Error exist here
$post = Image::make($fileNameToStore->getRealPath());
$post->text('The quick brown fox jumps over the lazy dog.');
$post->save();
getRealPath() is the method of SplFileInfo
See: https://www.php.net/manual/en/splfileinfo.getrealpath.php
If u want to use getRealPath(), try this:
Image::make(
$request->file('content')->getRealPath()
)->save('public/content',$fileNameToStore);

Picture not uploading to database but saving in folder

public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
On save this code returns column picture cannot be null. When i do the direct method without using the method array_from_post(), data is saved in the database but i can not save a post to be published at a future date.

Resources