1

What if I want to pass a variable like $k =1 (but the value of $K changes because it's a for loop counter) from view as an argument in a function in the controller without using the URL. The status column is represented in the database table "parcel" from 0-2. For example, in the foreach loop if the value of $k =0 then the controller function gets the value of $k, counts the number of times 0 appears in the database (status) using the count() method, then returns the value of count to the View.

View

@php
$status_arr = array("Item Accepted by Courier","Collected","Shipped");
@endphp

@foreach($status_arr as $k =>$v)
<!-- Parcel stages -->
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-warning 
                        text-uppercase mb-1">
                        {{$v}}
                    </div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                        {{$statuses}}
                    </div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-bicycle fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>
@endforeach

Controller

function total_parcels()
{
    $status = DB::table('parcels')
        ->where('status', '=', $k)
        ->count();

    return view('dashboard', ['statuses' => $status]);
}

Route

Route::get('dashboard', [DashboardController::class, 'total_parcels']);
11
  • 1
    use ajax request when variable change call api and pass the value Commented Oct 22, 2021 at 6:14
  • You can't pass a variable to the Controller, because the controller code runs before the view. You can however use a component to load a part of the view, where you can run code like in a controller Commented Oct 22, 2021 at 6:26
  • So, it is not possible to call the function in view? Commented Oct 22, 2021 at 6:37
  • 1
    You can create a helper function, you can create a component, you can use Ajax, but should not call a controller function from the view. Thats just not how MVC works. Commented Oct 22, 2021 at 6:39
  • With XMLHttpRequest you can send data from client / View data . Commented Oct 22, 2021 at 6:53

1 Answer 1

0

Can't you calculate statuses and their counts in the controller. Then pass the prepared data to the view for just "displaying" it?

I think you didn't have to pass data from view to controller.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.