I have 2 date fields in a table called prices in my database, the start and end time of a reservation (respectively).
In my controller using the following variable, I get these fields:
use DB;
use Illuminate\Http\Request;
use App\Http\Requests;
public function MyFunction(Request $request){
$desde = "08:00:00";
$hasta = "23:00:00";
$now = new \DateTime();
$price = DB::table('precios')
->join('complejo', 'complejo.id', '=', 'precios.complejo_id')
->get();
return view('confirmar',['price'=>$price, 'now'=>$now]);
}
Then in the view I show a field which is the amount of the price of a reservation, as follows:
<tr>
<td style="color: grey;">{{$prices->monto}}</td>
</tr>
And my problem comes now, it turns out that I don't know very well how to validate that the start_time and end_time fields are within a date range which is validated together with the current time.
That is, if the start time begins at 19:00:00 Hrs
and the end time ends at 23:00:00 Hrs
, and it is currently 4:35:00 p.m. , the price to be displayed should be the following:
'TABLA precios'
id|monto|hora_inicio|hora_fin
1|20000|19:00:00 |23:00:00
2|23000|15:00:00 |19:00:00
3|18000|08:00:00 |13:00:00
Said in the previous example, the price to show should be 23000, because the range of hours goes from 15:00:00
to 19:00:00 Hrs
, and currently it is 16:35:00 Hrs .
But on the other hand, that does not happen, the price that it shows me is always that of the first hour. The one of 15000, in the validation, without taking the time of truth, which is how I try to make it work, this in my controller:
$from = "08:00:00";
$now = Carbon::now();
$now->toTimeString();
$price = DB::table('precios')
->join('complejo', 'complejo.id', '=', 'precios.complejo_id')
->get();
//¿ES POSIBLE HACER ALGO SIMILAR COMO EN SQL?
/*EN SQL...
WHERE precio.hora_inicio AND precio.hora_fin
BETWEEN curTime() AND '17:00:00'*/
/*AHORA EN EL CONTROLADOR.
IF($price.hora_inicio && $price.hora_fin BETWEEN $now && '17:00:00')*/
/*ESTE ULTIMO (BETWEEN) REEMPLAZARLO POR UN OPERADOR QUE
REALICE LA MISMA FUNCION QUE BETWEEN EN SQL,
DE MOMENTO SE ME OCURRIÓ <= o >=*/
foreach ($price as $price) {
if ($price->hora_inicio && $price->hora_fin <= $now && '23:00:00') {
$valor = 23000;
}else if ($price->hora_inicio && $price->hora_fin <= $now && '17:00:00') {
$valor = 19000;
}else if ($price->hora_inicio && $price->hora_fin <= $now && '13:00:00') {
$valor = 15000;
}else{
$valor = 'No Aplica';
}
}
As an additional example, perform the following query against the database, obtaining the expected result. If I changed the system time that is being compared to in the query, it works every time.
using
date
if you left it with
Carbon
Other uses for
Carbon
https://styde.net/componente-carbon-dates-laravel-5/In laravel 5.x you can do it like this:
Laravel automatically parses the
carbon
and casts it tostring
. You can usefirst
since you will always have a single value, in case it is out of range, it will returnnull
. To access $price->amount;