I have a scenario where the record is like this:
date
2018-01-15
2018-01-16
Now what I need to do is just delete the very last date. I need to delete the query that has 2018-01-15.
My code is like this:
public function deletelatDate()
{
// $datedel = '2018-04-03';
$datedel = Attendance::sortBy('date', 'desc')->first();
// $query->sortBy('date', 'desc')->first();
DB::table('attendances')->where('date', $datedel )->delete();
return back()->with('success','Last attendance entries successfully deleted');
}
Do you have any suggestions on how am I able to fix this?
Thanks.
Use orderBy and get column date after getting first record
public function deletelatDate()
{
$datedel = Attendance::orderBy('date', 'asc')->first();
DB::table('attendances')->where('date', $datedel->date )->delete();
return back()->with('success','Last attendance entries successfully deleted');
}
Also check success of query before sending success message
You can use latest to get the latest record: https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset
public function deleteLatest()
{
// $datedel = today()->format('Y-m-d'); <-- use today's date
$datedel = '2018-04-03';
// find the record to delete
$toDelete = Attendance::where('date', $datedel)->oldest('date')->first();
// only perform delete if a record is found
if($toDelete) {
$toDelete->delete();
return back()->with('success','Last attendance entries successfully deleted');
}
return back()->with('error', 'No attendance entry found for this date: ' . $datedel);
}
Related
I am try to do is check if the booking is b/n request check_in and check_out date. if so exclude the booking with booked status =1.
$room->bookings()->where(function ($query) use ($check_in, $check_out, $statusCollect) {
$query->where('check_in','<=',$check_out)
->where('check_out','>=',$check_in)
->whereNotIn('book_status_id', $statusCollect)
});
but the problem is this query filter all inside table. how I can I use if statement in whereNotIn() or is there is other method.
what I need is if the check_in<=$check_in and $check_out >=check_out then give me booking table row then check the bookstatus, if it pass get me the row.
I hope I don't make it complicated:).
thanks
//controller
//first get data if data get then update the status
$data=$room->bookings()->where(function ($query) use ($check_in, $check_out) {
$query->where('check_in','<=',$check_out)
->where('check_out','>=',$check_in)
});
if(!empty($data) && $data!=''){
//you can use your table primary id to update the status
$modelObj=new model_name();
$updateArray=$modelObj->updatedById($data->id[
'book_status_id'=>statusCollect
]);
}
//model
function updatedById($id,$statusCollect){
return $this->where('id',$id)->update($statusCollect);
}
I have this column ('time_out') in a table of my database:
As you can see the time_out is null, and when I do this query:
$checkertimeout = Attendance::where('emp_id', $request->emp_id)
->where('attend_date', $date)->get(['time_out']);
I get this output:
[{"time_out":null}]
But when I use it in an if-else statement:
if ($checkertimeout->isEmpty())
{
echo "works";
}
else
{
echo "wont work";
}
It display won't work.
Any help is appreciated, I'm new to Eloquent query :)
First of all, when you do this:
$checkertimeout = Attendance
::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->get(['time_out']); // <---
You are getting a Collection of all the time_out fields of every Attendance models that match your criteria (the wheres). This means, something like this:
=> Illuminate\Database\Eloquent\Collection {#3323
all: [
App\Attendance {#3332
attend_date: "2019-10-06 22:01:29",
},
App\Attendance {#3340
attend_date: "2019-10-06 22:01:29",
},
App\Attendance {#314
attend_date: null,
},
],
}
You can get more info in the Eloquent section of the documentation.
Now, if your query is designed to get only one record, you could use the ->first() method instead of the get() one. This method will return the first Attendance object that matches your criteria.
$checkertimeout = Attendance
::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->first(); // <---
PS: If you only need to retrieve the time_out value, you could also add the ->select('attend_date') to the query:
$checkertimeout = Attendance
->select('time_out'); // <---
::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->first(); // <---
With these clarifications, let's go to your question. If you want to check if a field is null.. you could just make use of the PHP function is_null().
Using the collection
$checkertimeout = Attendance
::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->get(['time_out']);
if(is_null($checkertimeout->first()->time_out))
{
// ...
}
Using a single object
$checkertimeout = Attendance
->select('time_out'); // <---
::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->first(); // <---
if(is_null($checkertimeout->time_out)) // <----
{
// ...
}
Side note
As a side note, if you want to avoid the null results for that value, you could add another contraint in your query:
$checkertimeout = Attendance
::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->whereNotNull('time_out') // <-----
->get(['time_out']);
Hit it
$checkertimeout = Attendance::where('emp_id', $request->emp_id)
->where('attend_date', $date)->first();
At Blade File If Else
{{ $checkertimeout->time_out !=null ? 'Wont Work' : 'work' }} // when this condition $checkertimeout->time_out !=null true its run after "?" when its false it's running after ":" term
For Controller You can also dd or echo like below :
echo $checkertimeout->time_out !=null ? 'Wont Work' : 'work'; // you can replace echo with return too
First your query is getting all the records.
you should do like this in your query:
$checkerTimeOut = Attendance
::where([['emp_id', $request->emp_id], ['attend_date', $date]])
->first();
// This is to get a single record
then if you use if else statement you should also call the column you want to stablish.
if($checkerTimeOut->time_out->isEmpty()
{
dd('not empty');
}
else
{
dd('this record is empty');
}
you can also do like this:
if($checkerTimeOut->time_out)
{
dd('not empty');
}
else
{
dd('this record is empty');
}
or should be like this:
$checkerTimeOut->time_out
? 'not empty'
: 'this record is empty';
Event of the time_out is null, $checkertimeout variable is not empty. Because $checkertimeout is a collection. and it has one item in it.
As you can see like this.
[
{"time_out":null}
]
Since I don't know what you are trying to do, If you want the Attendance only where time_out is not null, You can do this.
$checkertimeout = Attendance::where('emp_id', $request->emp_id)
->where('attend_date', $date)
->whereNotNull('time_out')
->get(['time_out']);
Because $checkertimeout got a collection as
[
{"time_out":null}
]
so its no longer empty and it returns
"wont work"
I am working on a roll format for a laravel project.
I have successfully created the roll, and can update the roll status in the roll table which looks like this
|id|roll_id|member_id|status|created_at|updated_at|
One of my status is "Present/Voucher" using funds off a Voucher
I have the Voucher Table
|id|member_id|voucher|date|balance|created_at|updated_at|
When a user clicks on the present/voucher icon in the roll, the following is called in the controller
public function voucher($id)
{
$r = Roll::find($id);
if ($r != null)
{
$r->status = "V";
$r->save();
return redirect(action('RollController#index'))->with ('success', 'Member Paid with Vocuher');
}
return redirect(action('RollController#index'));
}
This works perfect, what I would like to know is how to insert a record into my Voucher table, while I can find the id record in the roll table, I need to pull that member_id so I can add this into the voucher table
For example if the Roll Record looks like this
|id|roll_id|member_id|Status|
|20|2|13|V|
I need to grab 13 are the Member_ID from roll record 20, so I can insert in the vouchers table
|id|member_id|voucher|date|balance
|2|13|Weekly Fees|currdate|-10
Please note the 10 is also stored in a settings table, so if I can grab from that table that would be great
Settings Table:
|id|Setting|Value|
|1|weekly Subs|10|
Thanks
You could first define model relationship.
Member
class Member extends Model {
public function vouchers()
{
return $this->hasMany('App\Voucher');
}
}
Roll
class Roll extends Model {
public function member()
{
return $this->belongsTo('App\Member');
}
}
Voucher
class Voucher extends Model {
public function member()
{
return $this->belongsTo('App\Member');
}
public function setting()
{
return $this->belongsTo('App\Setting');
}
}
Then you can execute fluently in controller, you should also use lockForUpdate and DB::transaction
public function voucher($id)
{
DB::transaction(function () use ($id) {
$roll = Roll::lockForUpdate()->find($id);
if ($roll != null) {
$roll->status = "V";
$roll->save();
$voucher = new Voucher();
$voucher->member_id = $roll->member_id;
...
// Correct me if I am wrong, form your table structure it looks like you linked table voucher and setting with 'value'
// I strongly recommend you to have setting_id as foreign key in table voucher
// So you could do
// $setting = Setting::where('Setting', 'weekly Subs')->where('Value', 10)->first();
// $voucher->setting_id = $setting->id;
$voucher->save();
return redirect(action('RollController#index'))->with ('success', 'Member Paid with Vocuher');
}
}
return redirect(action('RollController#index'));
}
I want to get all data in one column of the database (primary key) so that before I insert my data that is going to be inserted, I can check if its going to be duplicate or not.
Model:
public function getKeys() {
$this->db->select("key");
$this->db->from("database");
$result = $this->db->get();
return $result->result();
}
Controller:
public function Controler() {
$values = $this->MODEL_NAME->getKeys();
foreach ($values as $value) {
$array[] = $value->key;
}
# Compare new item to the current array
if (!(in_array($NEWITEM, $array))) {
# Insert
} else {
# Error catching
}
}
At insert time get all data from table.and then use condition on a particular field by which you want to check this data is already exist or not:
How can I retrieve the second to last row of the id provided?
public function show($id)
{
if (! Gate::allows('backup_view')) {
return abort(401);
}
$backup = Backup::findOrFail($id);
$second = Backup::select('id')->union($backup)->where('id', '<=' , $backup->id);
dd($second);
return view('admin.backups.show', compact('backup', 'secondlast'));
}
Please help.
I assume you are trying to return the variable $second. You are returning a variable called 'secondlast'. Try changing the name of the variable to $secondlast.
In order to return the second last record from the Backup Model, the following query should work assuming your primary key is 'id':
Backup::orderBy('id', 'desc')
->skip(1)
->take(1)
->first();