Laravel store (nullable validation error) - laravel

I've currently got the following store function
public function store()
{
$data = request()->validate([
'name' => 'required',
'description' => 'required',
'url' => ['required', 'url'],
'image' => ['nullable', 'image'],
]);
$DB1 = new \App\Part1();
$DB1->name = $data['name'];
$DB1->save();
$DB2 = new \App\Part2();
$DB2->db1_id = $DB1->id;
$DB2->description = $data['description'];
$DB2->url = $data['url'];
$DB2->image = $data['image'];
$DB2->save();
}
Every time I've got an empty image I get the following error:
ErrorException
Undefined index: image
I thought the nullable rule would be enough.
The only work around I found is to check if the image is empty but it feels like I am doing it wrong:
if (request('image')) {
$image = $data['image'];
} else {
$image = NULL;
}

Use isset or empty method or ?? operator
public function store()
{
$data = request()->validate([
'name' => 'required',
'description' => 'required',
'url' => ['required', 'url'],
'image' => ['nullable', 'image'],
]);
$DB1 = new \App\Part1();
$DB1->name = $data['name'];
$DB1->save();
$DB2 = new \App\Part2();
$DB2->db1_id = $DB1->id;
$DB2->description = $data['description'];
$DB2->url = $data['url'];
$DB2->image = isset($data['image']) ? $data['image'] : null;
// or $DB2->image = !empty($data['image']) ? $data['image'] : null;
// or $DB2->image = $data['image'] ?? $data['image'];
$DB2->save();
}
Hope this helps you

simply use the new PHP7 feature for in line checking and acting :
$DB2->image = $data['image']?? NULL;
its not about wrong or not, it is about the good and the better.
Now the ?? mean if the $data['image'] is null(false) then simply set NULL to $DB2->image.

Related

Upload image using CodeIgniter 4

PLease help me on how to upload image in the folder and the same time in the database with a random name.
There's an error: Call to a member function getName() on null.
Heres my code in controller
`public function actionInsert()
{
$destination = new DestinationModel();
$name=$this->request->getVar('name');
$place=$this->request->getVar('place');
$location=$this->request->getVar('location');
$category=$this->request->getVar('category');
$description=$this->request->getVar('description');
$latitude=$this->request->getVar('latitude');
$longitude=$this->request->getVar('longitude');
$image=$this->request->getFile('image');
$imageName = $image->getName();
$image->move('im/destination', $imageName);
if($place == 'Calapan City')
{
$place = 'Calapan';
}else if($category == 'Destination')
{
$category ='Destination';
}
$data = [
'name' => $name,
'place' => $place,
'location' => $location,
'category' => $category,
'image' => $place. '/'. $imageName,
'description' => $description,
'latitude' => $latitude,
'longitude' => $longitude
];
$destination->save($data);
return view('adding_place');
}`

Laravel 6 upload file

I have a big struggle about adding file uploading to an existing laravel 6 form.
I want to add the file url to database for future to be displayed (or downloaded).
When i try to do something nothing is happaning, nothing in DB nothing in file dir.
Here is my model:
protected $fillable = [
'age',
'last_rab',
'names',
'email',
'phone',
'last_pos',
'cv',
'msg',
'status'
];
Here is my Controller:
public function store(Request $request)
{
$request->validate([
'names' => 'required',
'age' => 'required',
'last_rab' => 'required',
'last_pos' => 'required',
'phone' => 'required',
'cv' => 'required|mimes:doc,docx,pdf,txt|max:2048',
'msg' => 'required'
]);
if ($request->captcha != 58) {
return redirect()->back()->withInput()->with('warning', 'Wrong');
}
$karieri = new Karieri;
$karieri->age = $request->age;
$karieri->last_rab = $request->last_rab;
$karieri->names = $request->names;
$karieri->email = $request->email;
$karieri->phone = $request->phone;
$karieri->last_pos = $request->last_pos;
if ($request->hasfile('cv')) {
$file = $request->file('cv');
$name = time().'.'.$file->extension();
$file->move(public_path() . '/storage/app/public', $name);
$data = $name;
$karieri->cv = json_encode($data);
}
$karieri->msg = $request->msg;
$karieri->status = 0;
$karieri->save();
return redirect()->back()->with('success', 'Thanks');
}
Can somebody say how to do this?

Cannot save my uploaded image to local disk folder

I am currently building a CRUD application using Laravel. It requires me to upload images and information but seems like there are some problems on storing the images to the localdisk folder.
Here is my controller code:
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
// $record = new Admin;
// return view('students.create');
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image'))
{
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->storeAs('public/images',$fileNameToStore);
// $file = $request->file('image');
// $extension =$file->getClientOriginalExtension();//getting image extensionimage
// $filename=time() ."." .$extension;
// $file->move('uploads',$filename->getClientOriginal);
// //getting from data base
}
else
{
// $lostitem->image = "";
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $request->image ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
The other information is saved. I hope to get help.
Change Your controller code to this:
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->move(public_path('images/'),$fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $request->image ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
And then access your image in the blade like this
<img src="{{ asset('images/'.$item->image) }}">
And make sure that you do have an folder named "images" in the public directory
Save the path of image in database
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->move(public_path('images/'),$fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $path ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
& show it
<img src="{{ asset('images/'.$item->image) }}">

"Creating default object from empty value"

I'm trying to insert data to Database, but got the error "Creating default object from empty value" and still don't understand, this error come from?
in My Controller
public function store(Request $request)
{
$request->validate([
'amount' => 'required',
'method' => 'required',
]);
$payrolls = new Payroll();
$payrolls->employee_id = auth()->user()->id;
$payrolls->account_id = auth()->user()->id;
$payrolls->employee_name = $request->get('employee_name');
$payrolls->description = $request->get('description');
$payrolls->account = $request->get('account');
$payrolls->amount = $request->get('amount');
$payrolls->method = $request->get('method');
$payrolls->save();
return response()->json(['created' => true]);
}
Any help? Thanks......
As #arm stated, you're having a typo in your code, which leads to the error you're getting.
The code below should make it working.
I would also suggest you to use $request->input('****'); instead of dynamic variables like you're doing $request->account;
public function store(Request $request)
{
$request->validate([
'amount' => 'required',
'method' => 'required',
]);
$payrolls = new Payroll();
$payrolls->employee_id = auth()->user()->id;
$payrolls->account_id = auth()->user()->id;
$payrolls->employee_name = $request->input('employee_name');
$payrolls->description = $request->input('description');
$payrolls->account = $request->input('account');
$payrolls->amount = $request->input('amount');
$payrolls->method = $request->input('method');
$payrolls->save();
return response()->json(['created' => true]);
}
You could also have a look at the Payroll::create(), which makes it easier to create a entry in the DB, instead of making a new Payroll(), and saving at the end. https://laravel.com/docs/5.7/eloquent#mass-assignment

ErrorException (E_ERROR) Trying to get property 'birthday' of non-object

public function profile_settings()
{
$student_information = Auth::user()->personal_information;
return view('StudentViews.profile_settings' , compact('student_information'));
}
public function save_profile_information(Request $request)
{
$flag = Auth::user()->personal_information;
if ($flag != "") {
$PersonalInformation = Auth::user()->personal_information;
$PersonalInformation->first_name = $request->first_name;
$PersonalInformation->last_name = $request->last_name;
$PersonalInformation->birthday = $request->birthday;
$PersonalInformation->email = Auth::user()->email;
$PersonalInformation->gender = Auth::user()->gender;
$PersonalInformation->occupation = Auth::user()->occupation;
$PersonalInformation->phone = $request->phone;
$PersonalInformation->website = $request->website;
$PersonalInformation->country = $request->country;
$PersonalInformation->province = $request->province;
$PersonalInformation->city = $request->city;
$PersonalInformation->description = $request->description;
$PersonalInformation->birthplace = $request->birthplace;
$PersonalInformation->marital_status = $request->marital_status;
$PersonalInformation->facebook = $request->facebook;
$PersonalInformation->twitter = $request->twitter;
$PersonalInformation->linkedin = $request->linkedin;
$PersonalInformation->google_plus = $request->google_plus;
$PersonalInformation->save();
$user = Auth::user();
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->phone = $request->phone;
$user->save();
}
else {
PersonalInformation::create([
'user_id' => Auth::user()->id,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'birthday' => $request->birthday,
'email' => Auth::user()->email,
'phone' => $request->phone,
'country' => $request->country,
'province' => $request->province,
'city' => $request->city,
'description' => $request->description,
'gender' => Auth::user()->gender,
'occupation' => Auth::user()->occupation,
'website' => $request->website,
'birthplace' => $request->birthplace,
'marital_status' => $request->marital_status,
'facebook' => $request->facebook,
'twitter' => $request->twitter,
'linkedin' => $request->linkedin,
'google_plus' => $request->google_plus,
]);
}
}
value = {{ ($student_information->birthday)?$student_information->birthday:""}}
it gives you an error because it has no value so replace the value in the blade page by the previous line, hope it will work.
Check by using is_object() function. It returns TRUE if it is an object.
And also check value is null or empty.
if (( $student_information != null) && (is_object($student_information))) {
// code here
// print any property here
}
Then Error will be fixed. If you print a property that doesn't contain value shows error like this.

Resources