lewis4u lewis4u - 17 days ago 5
Ajax Question

Laravel - pass ajax variables to model

In my User Model i have this getter method:

public function getWorkedHoursInRangeAttribute($start, $end)
{
$sum = [];
foreach($this->workedTimes as $item) {

if( ($item->start_time->gt($start)) && ($item->end_time->lt($end)) ){

array_push($sum, ceil($item->end_time->diffInMinutes($item->start_time->addMinutes($item->break_time_min))/60 * 4) / 4 );

}

}

return array_sum($sum);
}


And in my view i post this

function(start, end) {

$.ajax({
type: "POST",
url: '/users/workedhours',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: {"start": start.format("DD.MM.YYYY HH:mm"), "end": end.format("DD.MM.YYYY HH:mm")},


and i have this in my Controller

public function getWorkedHoursForRange(Request $request)
{

$start = Carbon::parse($request->start);
$end = Carbon::parse($request->end);


return response()->json(['msg' => $start], 200);
}


and this route:

Route::post('users/workedhours', 'UsersController@getWorkedHoursForRange');


How can i take this start and end variables from ajax to my Model method and make calculation?

I will probably need to do something in my Controller...but what?

UPDATE:

in view i have this foreach loop for my table:

<tbody>
@foreach ($users as $user)
<tr>
<td><a href="{{ url('/user', $user->id) }}">{{ $user->name }}</a></td>
<td>{{ $user->total_time_current_year }}</td>
<td>{{ $user->total_time_last_year }}</td>
<td>{{ $user->total_time_current_month }}</td>
<td>{{ $user->total_time_last_month }}</td>
<td>here i need the calculation for date range</td>
</tr>
@endforeach
</tbody>

Answer

You need two attributes in your model: start and end. That way you are able to access them in your accessor.

protected $start;
protected $end;

public function getWorkedHoursInRangeAttribute()
{
    $sum = [];
    foreach($this->workedTimes as $item) {

        if( ($item->start_time->gt($this->start)) && ($item->end_time->lt($this->end)) ){

            array_push($sum, ceil($item->end_time->diffInMinutes($item->start_time->addMinutes($item->break_time_min))/60 * 4) / 4 );

        }

    }

    return array_sum($sum);
}

You than make your AJAX call to the controller, loop through the users, set start and end vars to each user-model and return all users to the view. There you can access your accessor-attribute.

public function getWorkedHoursForRange(Request $request)
{

    $start = Carbon::parse($request->start);
    $end = Carbon::parse($request->end);

    $users = App\User::all();
    foreach($users as $user) {
        $user->start = $start;
        $user->end = $end;
    }


    return response()->json(['users' => $users], 200);
}