Thursday, March 16, 2017

From jQuery to blade variable

I know how to pass variables from blade template to jQuery modal, but I don't see how to do it other way around. I can check if the user is for example registered with:

@if(\Illuminate\Support\Facades\Auth::user())
    open modal with options
@else
    open basic modal message "you are not authorized"
@endif

But now, I'd like to check if the registered user is available to use the equipment on which he clicked. I have all the necessary model relations, so I could do something like Auth::user()->equipment->where('equipment_id', $equipment->id) != null...but the problem is that I can forward a variable to jQuery like data-equipment-id = ... and fetch it within a script...but how do I get it back to PHP variable so I can access it like:

@if(\Illuminate\Support\Facades\Auth::user())
    @if(Auth::user()->equipment->where('equipment_id', $equipment->id) != null)
        allowed!
    @else
        not allowed!
    @endif
@else
    open basic modal message "you are not authorized"
@endif

EDIT:

Here is how I forward data to modal:

@foreach($equipment as $instrument)
    <td>
        <a href="#" style="display: block;"
           data-href=""
           data-toggle="modal"
           data-target="#confirm-reservation"
           data-start-time=""
           data-end-time=""
           >

            @if($instrument->reservations
            ->where('reserved_from','<=', $scheduler_start_time)
            ->where('reserved_to','>=', $scheduler_start_time)->first() != null)

                HERE

            @else
                &nbsp;
            @endif
        </a>
    </td>
@endforeach

And then the modal script:

$('#confirm-reservation').on('show.bs.modal', function (e) {
    $(this).find('.dropdown-menu li').remove();
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    var startTime = moment($(e.relatedTarget).data('start-time')).utc();
    var endTime = moment($(e.relatedTarget).data('end-time')).utc();

    while (startTime < endTime) {
        $(this).find('.dropdown-menu').append('<li><a href="#">' + startTime.format("HH:mm") + '</a></li>');
        startTime.add(30, 'minutes');
    }

    $(document).on('click', '#confirm-reservation .dropdown-menu a', function () {
        $('#insert_text').text($(this).text());
        var href = $(e.relatedTarget).data('href');
        var time = moment().year(startTime.format("Y")).month(startTime.format("M")).date(startTime.format("D"))
                .hour(($(this).text().split(':')[0]) - 2).minutes($(this).text().split(':')[1]).seconds("0");

        console.log(time);

        $('.btn-ok').attr('href', href + '/' + time.unix());
    });
});



via Norgul

Advertisement