Home > front end >  Calling a class function in blade view laravel
Calling a class function in blade view laravel

Time:12-03

I have a CartController with the following function:

  public function getTotalCartPrice()
    {
        $totalCartPrice = 1;
        
        return $totalCartPrice;
    }

Cart.blade.php

<h3 >Cart total: {{ Cart::getTotalCartPrice }} </h3>

Routes

Route::resource('/cart', CartController::class);

Using this does not seem to display the total cart price and I get an error saying class "Cart" not found. I have attempted to change my route to this:

Route::get('/cartPrice', [CartController::class, 'getTotalCartPrice'])->name('getTotalCartPrice');

and then inside my blade view:

<h3 >Cart total: {{ route('getTotalCartPrice') }} </h3>

But I just get an output on the website:

Cart total: http://localhost/cartPrice

CodePudding user response:

To fix this error and display the total cart price, you can do the following:

In your CartController, add the Cart class to the use statement:

use Cart;

public function getTotalCartPrice()
{
    $totalCartPrice = 1;
        
    return $totalCartPrice;
}

In your blade view, you need to call the function using () after the function name:

<h3 >Cart total: {{ Cart::getTotalCartPrice() }} </h3>

In your routes file, you can use the resource method to create routes for the CartController class and its methods:

Route::resource('/cart', CartController::class);

In your blade view, you can use the route helper function to generate the URL for the getTotalCartPrice route and call the function using () after the function name:

<h3 >Cart total: {{ route('cart.getTotalCartPrice')() }} </h3>

After making these changes, the total cart price should be displayed on the website.

CodePudding user response:

I'm trying to help you.

To fix this error, you should add static keyword to function getTotalCartPrice in CartController. So it will be :

public static function getTotalCartPrice()
{
    $totalCartPrice = 1;
    
    return $totalCartPrice;
}

After that, in your view (blade) you should add Cart class in the top of the code. In this case I assume that your Cart controller class name is Cart, so the example is :

@php
    use App\Http\Controllers\Cart;
@endphp
// the rest of blade code

After that, you have to add () when you call the function from your blade

<h3 >Cart total: {{ Cart::getTotalCartPrice() }} </h3>

After that, the total cart must be shown.

  • Related