我试图在控制器中连接两个特定于类的变量,并将其传递给所有视图,而不是在每个控制器方法中重复相同的变量。
示例代码:
class ProductsController extends Controller
{
private $global_path; //Comes from .env
private $sub_folder = '/products_folder';
public function __construct()
{
//Frontend Image Path - to pass into all views
$frontend_path = $this->global_path.$this->sub_folder;
}
}
我想将'$ frontend_path'传递给控制器中创建的所有刀片视图,而不是像每个方法那样重复它
return view('example_view', compact('frontend_path');
我试过View :: share ...但是无法做到。
'$ sub_folder'变量在所有控制器中没有相同的值。
有没有办法让它成为可能?
对于您的代码,我认为您可以将其更改为
class ProductsController extends Controller
{
public $frontend_path;
public function __construct() {
$this->frontend_path = env('GLOBAL_PATH') . '/products_folder';
}
public function index()
{
$x = $this->frontend_path;
return view('index', compact('x'));
}
}
并直接使用它像$this->frontend_path
或像SELF::$frontend_path
下面
class ProductsController extends Controller
{
public static $frontend_path;
public function __construct() {
SELF::$frontend_path = env('GLOBAL_PATH') . '/products_folder';
}
public function index()
{
$x = SELF::$frontend_path;
return view('index', compact('x'));
}
}
要么
class ProductsController extends Controller
{
public static $frontend_path;
public function __construct() {
SELF::$frontend_path = env('GLOBAL_PATH') . '/products_folder';
view()->share('frontend_path', SELF::$frontend_path);
}
public function index()
{
return view('index');
}
}
在视野中
{{ $frontend_path }}