Laravel not updating null values to column - laravel

Migration
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->string('username',50)->unique();
$table->date('start_date');
$table->date('end_date')->nullable();
$table->timestamps();
});
Here start_date set as column type date and nullable
When running Insert function like below its inserting null values
$insert = [
'username' =>strtoupper(request('username')),
'password' =>Hash::make(request('password')),
'start_date' =>date('Y-m-d',strtotime(request('start_date'))),
];
if(request()->filled('end_date')){
$insert['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}
User::create($insert);
When Updating the same row left blank as end_date input,
$user = User::GetWithEncrypted(request('user_id'));
$update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
if(request()->filled('end_date')){
$update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}else{
$update['end_date'] = 'NULL';
}
$user->update($update);
In Table, it comes like below
How can I make it NULL like insert function in update?
My strict mode is false now, If I make it true it will throw an exception of invalid data for the end_date column.

Try replacing
}else{
$update['end_date'] = 'NULL';
}
with
}else{
$update['end_date'] = null;
}
'NULL' is a string whereas null is truly null.

you have 2 solution for this problem:
1.
$user = User::GetWithEncrypted(request('user_id'));
$update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
if(request()->filled('end_date')){
$update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}else{
$update['end_date'] = '".date('00:00:00')."';
}
$user->update($update);
2.
you have to set default in mysql database on end date field

First set table field to nullable()
Second set table field DEFAULT to NULL
Third:
$model->field = null;

Related

Laravel API: Timestamps (updated_at, created_at) are null

I have an API where the user creates the violation information of a certain driver and when I try to input a data into the table using Postman, the created_at column is NULL when it should not be. What could be the problem?
The code below is the lines of code Controller of when storing the data:
public function store(Request $request)
{
$rules=[
'Driver_ID'=>'nullable',
'Truck_ID'=>'nullable',
'Date_happened'=>'nullable',
'Time_happened'=>'nullable',
'offense_level'=>'nullable',
'violation_list'=>'required',
'status'=>'nullable',
'ml_violation'=>'nullable',
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response()->json($validator->errors(),400);
}
$data = $request->validate([
'Driver_ID'=>'nullable',
'Truck_ID'=>'nullable',
'Date_happened'=>'nullable',
'Time_happened'=>'nullable',
'offense_level'=>'nullable',
'status'=>'nullable',
'ml_violation'=>'nullable',
]);
// $violationsInformation = Violations::create($data);
$violation_list = json_decode($request->input('violation_list'));
$final_array = [];
foreach($violation_list as $key => $value){
array_push($final_array, [
// 'id'=>$id,
'Driver_ID'=> $request->input('Driver_ID'),
'Truck_ID'=> $request->input('Truck_ID'),
'Date_happened'=> $request->input('Date_happened'),
'Time_happened'=> $request->input('Time_happened'),
'violation_list_id'=> $value->id,
'offense_level'=> $request->input('offense_level'),
'status'=>$request->input('status'),
'ml_violation'=>$request->input('ml_violation'),
]);
}
//$quizRecords = Quiz_Records::create($final_array);
// $violationsInformation = Violations::create($data);
$violationsInformations = DB::table('violation_information')->insert($final_array); // Query Builder approach
return response(['message'=>"Violation's Information successfully created",
'error'=>false,
'error_code'=>200,
'line'=>"line".__LINE__."".basename(__LINE__),
'violationsInformations'=>$violationsInformations],200,[],JSON_NUMERIC_CHECK);
}
In database
You should set type of created_at : timestamp or datetime
And Options is (ON UPDATE)
And default is CURRENT_TIMESTAMP
sql :
ALTER TABLE `your_table`
CHANGE `created_at` `created_at` datetime NULL DEFAULT CURRENT_TIMESTAMP;
Instead of ->insert method use create method. The created_at and updated_at fields are updated by Eloquent (If using $table->timestamps() they are default NULL).

How to put the condition on User table with condition on subject table

Need to find the record with either first_name of the User table equal the keyword or subject of the TeacherSubject matches the keyword but 'step_completed' should equal '5' and 'is_approved' should equal '1' from the User table even if the orwhereHas condition is true.
$condition_array['radius'] = 25;
$condition_array['lat'] = $request->input('lat');
$condition_array['lng'] = $request->input('lng');
$condition_array['keyword'] = $request->input('keyword');
$sorting_type = $request->input('sorting_type');
$condition_array['filter'] = $request->input('filter');
if($sorting_type != ""){
if($sorting_type == 0){
$order_column = 'first_name';
$order_order = 'DESC';
}
if($sorting_type == 1){
$order_column = 'first_name';
$order_order = 'ASC';
}
}else{
$order_column = 'id';
$order_order = 'ASC';
}
$teachers = User::select('id','email','first_name','last_name','profile_picture','country_code','mobile')->with('teacherSubject')
->where(function($query) use($condition_array){
$query->where(['step_completed'=>5,'is_approved'=>1]);
$query->where(['first_name'=>$condition_array['keyword']]);
$query->orWhereHas('teacherSubject', function ($query1) use($condition_array){
$query1->where('subject',$condition_array['keyword']);
});
})
->orderBy($order_column,$order_order)
->get();
Need to find the record with either first_name of the User table equal the keyword or subject of the TeacherSubject matches the keyword but 'step_completed' should equal '5' and 'is_approved' should equal '1' from the User table even if the orwhereHas condition is true.
So if I would translate your statement into a query, I think it should look like this:
$teachers = User
::select('id','email','first_name','last_name','profile_picture','country_code','mobile')
->with('teacherSubject')
->where(['first_name'=>$condition_array['keyword']])
->orWhere(function($query) use($condition_array) {
$query->whereHas('teacherSubject', function($teacherQuery) use($condition_array) {
$teacherQuery->where('subject',$condition_array['keyword']);
})
->where(['step_completed'=>5,'is_approved'=>1]);
})
->orderBy($order_column,$order_order)
->get();
This way you have 2 conditions:
users.first_name == keyword OR
teacher_subject_user_id == users.id AND teacher_subject.subject = keyword AND users.step_completed == 5 AND is_approved == 1
If any of both is true, it will show up as a result.
Please let me know if it works :)

Store foreign key value in laravel

In Migration Table:
Schema::create('passws', function (Blueprint $table) {
$table->increments('id');
$table->integer('regist_id')->unsigned()->nullable();
$table->foreign('regist_id')->references('id')->on('regists');
$table->string('age');
$table->timestamps();
});
}
Regist Model - Mass Assignment Defined.
public function pass(){
return $this->hasOne('App\Passw');
}
In Controller
$name = $request->name;
$task = Regist::whereName($name)->get();
foreach ($task as $tasks){
$passw1->regist_id = $tasks->id;
}
$passw1->age = $request->age;
$regist = new Regist();
$regist->pass()->save($passw1);
When i store data, only age is getting stored but regist_id stored as null, (no error message or nothing). Here i'm sure controller shows "regist_id" => 1 and "age" => 25 when i use dd($passw1); regist_id is only not getting stores in DB table.
Where am i doing an error??
Try this
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
If you have more than one Regist for $name then try this
$regists = Regist::whereName($name)->get(); //it will give you a collection of Regist model
foreach ($regists as $regist){
$regist->pass()->create([
'age' => $request->age
]);
}
Check document here https://laravel.com/docs/5.6/eloquent-relationships#the-create-method

How to return one fields of updated rows?

I have the following query:
$updated = ResultTest::whereIn("client_id", $request->id)->update(array("mode" => 1));
Now it returns $update flag (1|0) if rows was updated.
How to get array of fields client_id instead boolean value?
Use tap function:
$results = ResultTest::whereIn("client_id", $request->id);
$updated = tap($results)->update(array("mode" => 1));
return $results->pluck('client_id');
https://medium.com/#taylorotwell/tap-tap-tap-1fc6fc1f93a6

Laravel how to get a Model by two parameters

Hi I'm new to Laravel and got stuck in a Problem.
I have a model Contact
class Contact extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'contacts';
}
The table have these fields:
user_id (int)
contact_id (int)
...
these two fields represent the primary key.
In the ContactsController I have the function store in wich I create or update the database:
public function store()
{
switch (Input::get('type')){
case 'make_contact_request':
$user = User::where('email', '=', Input::get('login'));
$request_self = new Contact;
$request_contact = new Contact;
$request_self->user_id = Auth::user()->id;
$request_self->contact_id = $user->id;
$request_self->status = 2;
$request_self->message = Input::get('message');
$request_contact->user_id = $user->id;
$request_contact->contact_id = Auth::user()->id;
$request_contact->status = 1;
$request_contact->message = Input::get('message');
$request_self->save();
$request_contact->save();
break;
case 'answer_contact_request':
$request_self = Contact::where('user_id', '=',Input::get('contact_id'))->where('contact_id', '=', Auth::user()->id)->first();
//$request_self = Contact::whereRaw('user_id = '.Input::get('contact_id').' AND contact_id = '.Auth::user()->id.' ');
$request_contact = Contact::whereRaw('user_id = '.Auth::user()->id.' AND contact_id = '.Input::get('contact_id').' ');
$request_self->status = 3;
$request_contact->status = 3;
$request_self->save();
$request_contact->save();
break;
}
}
I tried two different ways to get the Contact Object for the request_self Object and I get the following error:
message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `contacts` set `status` = 3, `updated_at` = 2014-08-02 16:16:56 where `id` is null)"
for the request_contact Object it throws a fatal error (don't get the description) and close the session.
At the end I am at the beginning of laravel so I hope the solution is pretty easy to find :) but I dont even really know for what to search.
Update:
At the end I fixed the Problem with the update function.
case 'answer_contact_request':
$request_self = Contact::where('user_id', '=',Input::get('contact_id'))->where('contact_id', '=', Auth::user()->id)->update(array('status' => 3));
$request_contact = Contact::where('user_id', '=', Auth::user()->id)->where('contact_id', '=', Input::get('contact_id'))->update(array('status' => 3));
break;
I think you can add
public function scopeComposite($query, $user_id, $contact_id)
{
return $query->where('user_id', '=', $user_id)->where('contact_id', '=', $contact_id);
}
and then you can get the contact with:
$request_self = Contact::composite(Input::get('contact_id'), Auth::user()->id)->get();
source: http://laravel.com/docs/eloquent#query-scopes
I'm not sure you can make it like this.
There is a way to make sure it works:
add a column id ( auto increment, primary ) and make the group ( contact_id, user_id ) unique and you can use query scopes and id based

Resources