简体   繁体   中英

How to call a controller from view in laravel 5

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.

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.

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.

在此处输入图片说明

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

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)}}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM