-1

I am using Laravel 5 in which i have to call a controller from view blade. But it showing me parse error. Please find my code.

Controller name:ReportController(path=app/Http/Controllers/Admin/ReportController)

<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
//send email use helper
use App\Helpers\MyHelperFunction;

 public static function my($args){
        // do your stuff or return something.
        echo $args."I am called on view.";
    }
?>

View:customerorders.blade.php

<?php 
use App\Http\Controllers\Admin\ReportController;
     echo ReportController::my('hello'); 
?>

I facing this error:

Method Illuminate\View\View::__toString() must not throw an exception, caught ErrorException: Parse error: syntax error, unexpected 'use' (T_USE) (View:/opt/lampp/htdocs/buddyiq_dev/resources/views/Admin/reports/customerorders.blade.php)

I refer above code from below stack url.

How to call a controller function inside a view in laravel 5

Please help me to resolve this issue.

Amit Gupta
  • 2,771
  • 2
  • 17
  • 31

4 Answers4

0

You could try using ajax to call to function in a controller, then get the respones and push it to view. About respones, remember to put return in your function.

Cong LB
  • 108
  • 5
0

If your motivation for calling a controller method is just to output a string a controller may be inappropriate. Controllers bind models and views together.

enter image description here

image source: Basic Laravel 5 MVC

Views really shouldn't be aware of controllers methods. You might be better off investigating view helper methods.

This is also answered in the question you link to

If you have a function which is being used at multiple places you should define it in helpers file

This Q/A is helpful Best practices for custom helpers on Laravel 5

Lex
  • 4,749
  • 3
  • 45
  • 66
-1

So I just tried this on one of my Laravel setups. I'm not sure if it's the best approach but it works.

Declare your function as

public static function my($args)
{
       echo $args."I am called on view.";
}

which you already did. then call it from the view as {{App\Http\Controllers\Admin\ReportController::my($args)}}

AceKYD
  • 1,100
  • 1
  • 10
  • 14
-2

Use the absolute path instead relative path, you can use this as like below,

 \App\Http\Controllers\Admin\ReportController

but you have used App\Http\Controllers\Admin\ReportController, please change it in every places.

Viraj Amarasinghe
  • 911
  • 10
  • 20