"Trying to get property 'id' of non-object" - php

I want to get the id of the cycles table so that I can store to the mortalities table.
SELECT `id` FROM `cycles`
WHERE `date_start_raise` <= request('date_input')
AND `date_end_raise` >= request('date_input')`
Converted to Laravel Query Builder:
<?php
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise', '<=', request('date_input'))
->where('date_end_raise', '>=', request('date_input'))
->get();
request('date_input') was from the MortalityController
MortalityController.php
public function store(Request $request)
{
$this->validate($request, array(
'date_input' => 'required|date',
'number_of_mortality' => 'required|numeric',
'chicken_age' => 'required|numeric'
) );
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise', '<=', request('date_input'))
->where('date_end_raise', '>=', request('date_input')) ->get();
return Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => request('chicken_age'),
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $cycle->first()->id,
'user_id' => Auth::id()
]);
}
After that I got an error:
"message": "SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect
integer value: '[]' for column 'cycle_id' at row 1 (SQL: insert into
mortalities (date_input, number_of_mortality, chicken_age,
cause_of_death, cycle_id, user_id, updated_at, created_at)
values (2018-09-04, 25, 2, , [], 1, 2018-11-28 07:38:01, 2018-11-28
07:38:01))"
I fix the error but new error appeared
"message": "Trying to get property 'id' of non-object"
Can anyone please help me?

You need to get values from $request object by using $request->get('your_id') or
$request->input('your_id')
Try this..!!
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise','<=',$request->get('date_input'))
->where('date_end_raise','>=',$request->get('date_input'))
->first();
OR
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise','<=',$request->get('date_input'))
->where('date_end_raise','>=',$request->get('date_input'))
->get();
then
foreach($cycle as $value){
//extract data from $value
}
Hop its work for you ...

use like that (u are passing collection to insert)
$cycle = DB::table('cycles')->select('id')
->where('date_start_raise','<=',request('date_input'))
->where('date_end_raise','>=',request('date_input'))
->first()->id;

Check this !!
return Mortality::create([
'date_input' => request('date_input'),
'number_of_mortality' => request('number_of_mortality'),
'chicken_age' => request('chicken_age'),
'cause_of_death' => request('cause_of_death'),
'cycle_id' => $cycle->first()->id,
'user_id' => Auth::id()
]);`

Related

hide records with controller

How can I hide records from my controller? i need to hide the records if the column 'retiro' is not null.
Controller:
public function retiro (Request $request){
$data = [
'category_name' => 'datatable',
'page_name' => 'miscellaneous',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$records = Registro::where('retiro', '<>', 'on')->get();
return view('retiro',compact('records'))->with($data);
}
if 'retiro' == 'on' should hide the record
the problem is that when printing the records it does not show anything.
help pls
You can pass all the variables as the second parameter on the view() using compact instead of doing it separately using the function with.
public function retiro (Request $request){
$data = [
'category_name' => 'datatable',
'page_name' => 'miscellaneous',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
];
$records = Registro::whereNotNull('retiro')
->where('retiro','=','on')
->get();
return view('retiro',compact('records','data'));
}

laravel 8 update eloquent relationships hasmany

My UPDATE function is as follows; I manually set some fields in the users table. In other words, it is necessary to update only the name part from the incoming request. If the lawyer has been removed from the edit form, it must also be removed from the users table. If the lawyer name has been updated, it should also be updated in the table.
How can I complete the update process.
public function update(Request $request, LegalPursuit $legalPursuit, $id)
{
$request->validate([
'BRANCH_ID' => 'required',
'MAIN_ACCOUNT_ID' => 'required',
'DEPOSITOR_ID' => 'required',
'ACCOUNT_HOLDER' => 'required|max:255',
'CURRENT_SCREEN_BALANCE' => 'required',
'TRL_EQUIVALENT' => 'required'
]);
//dd($request->all());
if($request->input('PROVISION') == 'on'){
$request->request->add(['PROVISION' => 'yes']);
}
$request->FOLLOW_UP_DATE = \Carbon\Carbon::parse($request->input('FOLLOW_UP_DATE'))->format('Y-m-d');
$request->DATE_OF_ATTORNEY_SUBMISSION = \Carbon\Carbon::parse($request->input('DATE_OF_ATTORNEY_SUBMISSION'))->format('Y-m-d');
$request->PROVISION_DATE = \Carbon\Carbon::parse($request->input('PROVISION_DATE'))->format('Y-m-d');
$request->request->add(['FOLLOW_UP_DATE' => $request->FOLLOW_UP_DATE]); //dd request
$request->request->add(['DATE_OF_ATTORNEY_SUBMISSION' => $request->DATE_OF_ATTORNEY_SUBMISSION]); //dd request
$request->request->add(['PROVISION_DATE' => $request->PROVISION_DATE]); //dd request
if(is_array($request->input('LAWYERS')) AND !empty($request->input('LAWYERS'))){
$lawyerArray = $request->input('LAWYERS');
//dd($lawyer_array);
$lawyerArray->each(function($lawyer) use ($user) {
$user->lawyerArray()->updateOrCreate(
[
'legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]
);
}
);
for($x = 0; $x < count($request->input('LAWYERS')); $x++){
User::updateOrInsert(
['legalpursuit_id' => $id],
[
'role_id' => 1,
'name' => $request->input('LAWYERS'),
'email' => 'aa#'.rand().'.com',
'email_verified_at' => now(),
'password'=> Hash::make('1q2w3e4r'),
'department' => 'Avukat',
'gender' => 'Kadın',
'marital_status' => 'Bekar',
'job' => 'Avukat',
'phone' => '+9055555',
'internal_no' => '0',
'active' => '0',
'deleted' => '0'
]);
}
/*foreach($lawyer_array as $lawyer) {
$updateLaywer =
}
dd($updateLaywer);
/*
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$lawyersChanged = DB::table('users')
->whereIn('id', $getUsers)
->update(
[
'name' => ''
]
);
*/
//echo "asdfasdfasdf";exit;
/*
$lawyersChanged = User::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('LAWYERS')]
);
//echo $lawyersChanged; exit;*/
}else{
$getUsers = DB::table('users')
->select(['users.id'])
->leftJoin('legalpursuit', 'users.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->get();
$getUsers->delete();
//echo "aaaaaaaa";exit;
}
if(is_array($request->input('GUARANTORS')) AND !empty($request->input('GUARANTORS'))){
echo "asdfasdfadsf";exit;
$guarantorsChanged = Guarantors::updateOrCreate(
['legalpursuit_id' => $id],
['name' => $request->input('GUARANTORS')]
);
}else{
//echo "hdfghdfghdfghdfgh";exit;
$getGuarantors = DB::table('guarantors')
->select(['guarantors.id'])
->leftJoin('legalpursuit', 'guarantors.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
//dd($getGuarantors);
//$getGuarantors->delete();
}
if($request->input('REMOVE_FILES')){
$getCurrentFiles = DB::table('files')
->select(['files.ID'])
->leftJoin('legalpursuit', 'files.legalpursuit_id', '=', 'legalpursuit.ID')
->where('legalpursuit.ID', '=', $id)
->delete();
}
LegalPursuit::where('ID',$id)->update(
$request->only(
[
'BRANCH_ID',
'MAIN_ACCOUNT_ID',
'DEPOSITOR_ID',
'ACCOUNT_HOLDER',
'FOLLOW_UP_DATE',
'CURRENT_SCREEN_BALANCE',
'CURRENCY',
'TRL_EQUIVALENT',
'DATE_OF_ATTORNEY_SUBMISSION',
'PROVISION',
'PROVISION_DATE',
'LAWSUIT_ID',
'ASSURANCE',
'DEED_PLATE',
'APPRAISAL_VALUE',
'LIEN_PRICE',
'DETERMINED_GUARANTEES',
'LEVY_INFO',
'LAST_STATUS'
]
)
);
if($request->hasFile('FILES')) {
foreach ($request->file('FILES') as $fl) {
$fileName = time().'_'.$fl->getClientOriginalName();
$fileExt = $fl->getClientOriginalExtension();
$filePath = $fl->store('public/files');
$filex = new Files;
$filex->legalpursuit_id = $id;
$filex->name = $fileName;
$filex->type = $fileExt;
$filex->label = $filePath;
$filex->descript = $fileName.'-'.$fileExt.'--'.$filePath;
$filex->status = 'on';
$filex->save();
}
}
return redirect()->back()->with('success', 'Kayıt Başarılı Bir Şekilde Güncellendi...');
}

How to select field name using with relation in laravel

I am trying to get field name using with relation:
My Code:
public function getAllUsers()
{
$users = User::with('userBasicInfo','roles:name')->get();
return response([
'status' => true,
'message' => "All Users",
'total' => count($users),
'data' => $users
], 200);
}
when i simply use $users = User::with('userBasicInfo','roles)->get();
it returns my record accurately and when I used $users = User::with('userBasicInfo','roles:name')->get();
It returns my null array of roles I also want to display name using roles: name but it returns nothing.
You should try this:
public function getAllUsers()
{
$users = DB::table('users')
->select('users.name','roles.name')
->join('userBasicInfo', 'users.userbasicinfo_id', '=', 'userBasicInfo.id')
->join('roles', 'users.roles_id', '=', 'roles.id')
->get();
OR
$users = User::with(['userBasicInfo','roles:name'])->get();
return response([
'status' => true,
'message' => "All Users",
'total' => count($users),
'data' => $users
], 200);
}

Laravel DB table and eloquent method updateOrCreate

DB::table("mytable")->updateOrCreate([
'user_id' => $user_id,
'active' => 1,
'created_at' => Carbon::now()
]);
But this code return me error:
Call to undefined method
Illuminate\Database\Query\Builder::updateOrCreate()
So, according to this answer link (user stanb) I added:
protected $table = 'mytable';
And change code:
DB::table($this->table)->updateOrCreate([...
But still I have this same error
DB::table('table name')
->updateOrInsert(
['email' => 'admin#admin.com', 'name' => 'Admin'],
['id' => '7']
);
I disagree with the other answer, we can use query builder to insert or update.
It's Eloquent method, so you need to use model. Also, you need to pass two arrays as parameters:
Model::updateOrCreate([
'user_id' => $user_id
],
[
'active' => 1,
'created_at' => Carbon::now()
]);
In this example, if there is a record where user_id = $user_id, the record will be updated.

Error "No function matches the . . ." Laravel Transaction With PostgreSQL

I using laravel 5.3 with PostgreSQL and i have code like this
public function store(array $request)
{
DB::transaction(function () use ($request) {
$phoneData = [
'phone_no' => $request['phone'],
'created_by' => $request['sdm_employee_id'],
'updated_by' => $request['sdm_employee_id'],
'created_stamp' => Carbon::now()->toDateString(),
'updated_stamp' => Carbon::now()->toDateString(),
];
$phone = DonorPhone::create($phoneData);
if (!$phone) {
throw new \Exception('Phone not created for account');
}
$data = [
'phone_id' => $phone->id,
'full_name' => $request['name'],
'address' => $request['address'],
'email' => array_key_exists('email', $request) ? $request['email'] : null,
'register_date' => Carbon::now()->toDateString(),
'marketer_id' => (int) $request['sdm_employee_id'],
'created_by' => (int) $request['sdm_employee_id'],
'updated_by' => (int) $request['sdm_employee_id'],
'company_id' => 2,
'user_status' => 1,
'note' => 'Add donor from sales track apps',
'phone_no_full' => $request['phone'],
'created_stamp' => Carbon::now()->toDateString(),
'updated_stamp' => Carbon::now()->toDateString(),
];
$contact = self::create($data);
if (!$contact) {
throw new \Exception('Contact not created');
}
$phone->user_id = (int)$contact->id;
$phone->save();
$target = new Target;
$target->updateAchievement($data['sdm_employee_id'], $this->tragetType, Carbon::now()->year, Carbon::now()->month);
throw new \Exception('Contact not created');
});
}
When create contact i got error
SQLSTATE[42883]: Undefined function: 7 ERROR: function php_donor_phone_get_all(integer) does not exist\nLINE 1: SELECT php_donor_phone_get_all(NEW.id)\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.\nQUERY: SELECT php_donor_phone_get_all(NEW.id)\nCONTEXT: PL\/pgSQL function public.php_donor_tr_full_text() line 6 at assignment (SQL: insert into \"public\".\"php_donor_personal\" (\"full_name\", \"address\", \"email\", \"register_date\", \"marketer_id\", \"created_by\", \"updated_by\", \"company_id\", \"user_status\", \"phone_no_full\", \"created_stamp\", \"updated_stamp\") values . . .
I check for function php_donor_phone_get_all is exist and my database username have a grant to execute this function. This seems to relate to a specific data type when calling the function, passing not an integer, but I do not know how to ensure that data in passing is an integer. There is a hint for me? Please help.

Categories