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

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.

Related

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'total_item' cannot be null

I’m trying to create payment integration snap token request, which is a local payment mostly like PayPal. the problem is I couldn’t get request from datatables transactions, and the error output is Integrity constraint violation: 1048 Column 'total_item' cannot be null.
controller.php
public function index()
{
return view('midtrans.index');
}
public function payment(Request $request)
{
// Set your Merchant Server Key
\Midtrans\Config::$serverKey = env('MIDTRANS_SERVER_KEY');
// Set to Development/Sandbox Environment (default). Set to true for Production Environment (accept real transaction).
\Midtrans\Config::$isProduction = false;
// Set sanitization on (default)
\Midtrans\Config::$isSanitized = true;
// Set 3DS transaction for credit card to true
\Midtrans\Config::$is3ds = true;
$penjualan = Penjualan::find(session('id_penjualan'));
$detail = PenjualanDetail::where('id_penjualan', $penjualan->id_penjualan)->get();
$validator = \Validator::make(request()->all(), [
'id_penjualan' => 'required|string|max:255',
'id_member' => 'required|string|max:255',
'total_item' => 'required|string|max:255',
'total_harga'=> 'required| numeric | min:0.01',
'ppn' => 'required|numeric|min:1',
'diskon' => 'required|numeric|min:1',
'bayar' => 'required|numeric|min:1',
'diterima' => 'required|int|numeric|min:1',
]);
// $validated = $request->validated();
\DB::transaction(function() use($request) { // use($validated)
$penjualan = Penjualan::create([
'id_penjualan' => $request->id_penjualan, // $validated['id_penjualan']
'id_member' => $request->id_member,
'total_item' => $request->total_item,
'total_harga' => $request->total_harga,
'ppn' => $request->ppn,
'diskon' => $request->diskon,
'bayar' => $request->bayar,
'diterima' => $request->diterima,
'id_user' => auth()->user()->id // Auth::user()->id,
]);
$params = array(
'transaction_details' => array(
'order_id' => rand(),
'gross_amount' => $penjualan->bayar,
),
'item_details' => array(
[
'id' => $penjualan->id_penjualan,
'price' => $penjualan->harga_jual,
'quantity' => $penjualan->jumlah,
'name' => $penjualan->nama_produk
]
),
'customer_details' => array(
'first_name' => $request->get('uname'),
'last_name' => '',
'email' => $request->get('email'),
'phone' => $request->get('number')
),
);
$snapToken = \Midtrans\Snap::getSnapToken($params);
$penjualan->snap_token = $snapToken;
$penjualan->save();
$this->response['snap_token'] = $snapToken;
});
return view('midtrans.payment', ['snap_token'=>$snapToken]);
}
public function payment_post(Request $request)
{
$json = json_decode($request->get('json'));
$penjualan = Penjualan::findOrFail($request->id_penjualan);
$penjualan->status = $json->transaction_status;
$penjualan->uname = $request->get('uname');
$penjualan->email = $request->get('email');
$penjualan->number = $request->get('number');
$penjualan->transaction_id = $json->transaction_id;
$penjualan->order_id = $json->order_id;
$penjualan->gross_amount = $json->gross_amount;
$penjualan->payment_type = $json->payment_type;
$penjualan->payment_code = isset($json->payment_code) ? $json->payment_code : null;
$penjualan->pdf_url = isset($json->pdf_url) ? $json->pdf_url : null;
return $order->save() ? redirect(url('/'))->with('alert-success', 'Order berhasil dibuat') : redirect(url('/'))->with('alert-failed', 'Terjadi kesalahan');
}
does anyone can help what I’m missing? thanks

laravel multiple images update function

i am new for laravel, i am not able to save the files in database on update function can any one help me for this,I have two related tables where one is a ticekt table and the other a one a documents table. In the documents table are the columns id, doc_name,doc_path,user_id and service_id. I'm trying to edit multiple images when editing a service. documents table not updating remaining things update successful
Cread service code
public function store(Request $request)
{
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()){
return back()->with('warning','please Fill manadatory fields');
} else {
//$dates = ;
//dd($dates);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'ticket_id' => strtoupper(str_random(10)),
'email'=>$request->input('email'),
'typeofservice' => $request->input('typeofservice'),
'companyname' => $request->input('companyname'),
'representative' => $request->input('representative'),
'phone' => $request->input('phone'),
'services' => $request->input('services'),
'applicant' => $request->input('applicant'),
'remark' => $request->input('remark'),
'ticket_submit_date' => date('d-M-Y'),
'status' => "1",
]);
//dd($ticket);
$ticket->save();
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($ticket) {
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
//return $last_id;
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
$users = User::where('id','=',$ticket_details->user_id)->first();
$ticketid = $ticket_details->ticket_id;
$username = $users->first_name.' '.$users->last_name;
$mdata = ['ticketid'=>$ticketid,'name'=>$username];
$user['to']= $users->email;
Mail::send('emails.user_create_application',$mdata,function($message) use ($user){
$message->to($user['to']);
$message->subject('User Create Application');
});
return back()->with("success","Service Requiest Created Successfully! your tracking id:#$ticket->ticket_id" );
}
}
}
For uddate function given below
public function udateuserticket(Request $request, $id){
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$email = $request->email;
$typeofservice = $request->typeofservice;
$companyname = $request->companyname;
$representative = $request->representative;
$phone = $request->phone;
$services = $request-> services;
$applicant = $request->applicant;
$remark = $request->remark;
$updateuserticket = Ticket::where('id','=',$id)->update([
'email' => $email,'typeofservice' =>$typeofservice, 'companyname' => $companyname, 'representative' => $representative,'phone' => $phone,'services' => $services, 'applicant' => $applicant, 'remark' => $remark ]);
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($updateuserticket){
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
if(File::exists($destinationPath)){
File::delete($destinationPath);
}
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
//$users = User::where('id','=',$ticket_details->user_id)->first();
//$ticketid = $ticket_details->ticket_id;
//$username = $users->first_name.' '.$users->last_name;
return redirect('showtickets')->with('success','Ticket Updated Successfully!');
}
}
for view
#foreach( $documents as $doc )
<div class="col-md-6">
<input id="documents" type="file" class="form-control" name="documents[]" value="" required>
<img src="{{ url('/') }}/public/documets/{{ $doc->doc_path }}" alt="user-img" class="img-width" style="width:30px;height:30px;">
</div>
#endforeach
This one update only details not able to update documents can you please guid anyone where i am wrong

How to Create Multiple input with laravel API?

I want to make an report API with the option of being able to do multiple inputs for violators data, crime scene photo data and personnel data.
I've tried to code like below, but still can't do multiple input. What is the correct way to create multiple inputs in laravel API (with file upload) ?
Controller
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->category_id !== 4 && $request->violator_photo) {
$violators = $request->file('violator_photo');
$violators = [];
foreach($violators as $key => $value) {
if($request->hasFile('violator_photo')) {
$violator_photo = $request->hasFile('violator_photo');
$fileName = time().'_'.$violator_photo[$key]->getClientOriginalName();
$filePath = $violator_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
}
$data = new Violator();
$data->report_id = $report->id;
$data->name = $request->violator_name[$key];
$data->photo = $filePath[$key];
$data->age = $request->violator_age[$key];
$data->phone = $request->violator_phone[$key];
$data->save();
}
}
$files = $request->file('crime_scene_photo');
$files = [];
foreach($files as $key => $value) {
if($request->hasFile('crime_scene_photo')) {
$crime_scene_photo = $request->hasFile('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
}
$data = new CrimeScenePhoto();
$data->report_id = $report->id;
$data->path = $path[$key];
$data->caption = $request->caption[$key];
$data->save();
}
if (\Auth::user()->unit_id == 2 && $request->personel) {
foreach ($request->personel as $key => $value) {
$report->members()->sync($request->personel[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report,
$request->all()
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
And here is how I tested in postman.
Solved. i changed my code to like this and it work.
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->hasFile('violator_photo')) {
foreach($request->file('violator_photo') as $key => $value) {
$vio_photo = $request->file('crime_scene_photo');
$fileName = time().'_'.$vio_photo[$key]->getClientOriginalName();
$filePath = $vio_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
Violator::create([
'report_id' => $report->id,
'name' => $request->violator_name[$key] ?? null,
'photo' => $filePath ?? null,
'age' => $request->violator_age[$key] ?? null,
'phone' => $request->violator_phone[$key] ?? null
]);
}
}
if ($request->hasFile('crime_scene_photo')) {
foreach($request->file('crime_scene_photo') as $key => $value) {
$crime_scene_photo = $request->file('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
CrimeScenePhoto::create([
'report_id' => $report->id,
'path' => $path ?? null,
'caption' => $request->caption[$key] ?? null
]);
}
}
if (\Auth::user()->unit_id == 2 && $request->personel_id) {
foreach ($request->personel_id as $key => $value) {
$report->members()->attach($request->personel_id[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report, $report->members, $report->violators, $report->photos
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}

Laravel store (nullable validation error)

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.

creating default object from empty value in laravel 5

I'm trying to make two functions in controller that have post action and that are in the same page.
My Controller
public function store(Request $request)
{
$status = DB::table('analytics')->where('dienstleistung', '!=', '')->get();
//Save data
$rules = [
'site_id' => 'required',
'dienstleistung' => 'required',
'objekt' => 'required',
'zimmer' => 'required',
'vorname' => 'required',
'name' => 'required',
'strasse' => 'required',
'ort' => 'required',
'plz' => 'required',
'tel' => 'required',
'email' => 'required|email',
'reinigungstermin' => 'required',
'gekommen' => 'required',
'message' => 'required',
'status' => 'required',
'answer' => 'required',
'notiz' => 'required',
'userId' => 'required',
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::to('anfrage')
->withErrors($validator)
->withInput();
}
else {
$anfrage = new Analytic();
$anfrage->site_id = Input::get('site_id');
$anfrage->dienstleistung = Input::get('dienstleistung');
$anfrage->objekt = Input::get('objekt');
$anfrage->zimmer = Input::get('zimmer');
$anfrage->vorname = Input::get('vorname');
$anfrage->name = Input::get('name');
$anfrage->strasse = Input::get('strasse');
$anfrage->ort = Input::get('ort');
$anfrage->plz = Input::get('plz');
$anfrage->tel = Input::get('tel');
$anfrage->email = Input::get('email');
$anfrage->reinigungstermin = Input::get('reinigungstermin');
$anfrage->gekommen = Input::get('gekommen');
$anfrage->message = Input::get('message');
$anfrage->status = Input::get('status');
$anfrage->answer = Input::get('answer');
$anfrage->notiz = Input::get('notiz');
$anfrage->userId = Input::get('userId');
try {
$anfrage->save();
flash()->success(trans('app.success'));
return Redirect::to('anfrage');
} catch (\Exception $e) {
Log::writeException($e);
return Redirect::to('anfrage')
->withErrors($e->getMessage())
->withInput();
}
}
}
public function editItem(Request $request) {
$anfrages = Analytic::find($request['id'] );
$anfrages->status = $request->status;
$anfrages->answer = $request->answer;
$anfrages->notiz = $request->notiz;
$anfrages->save();
return response ()->json( $anfrages );
}
My route:
Route::post('anfrage', 'AnfrageController#store');
Route::post ( 'anfrage', 'AnfrageController#editItem' );
EditItem function is OK, it makes changes when I want to edit data, but when I want to store data, message being displayed is:
creating default object from empty value
So, I need to leave active only one of these function, both are not working.

Resources