我希望有一个公共变量$users = User::all();
,所以我可以在控制器内的不同方法中使用它,它不会这样工作:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminController extends Controller
{
public $users = User::all();
public function __construct() {
$this->middleware('auth');
}
public function index()
{
return view('admin.index');
}
public function showUsers()
{
return view('admin.users', compact('users'));
}
}
我收到此错误:常量表达式包含无效操作
我做错了什么?
答案 0 :(得分:4)
尝试将分配添加到__construct()
功能中:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminController extends Controller
{
public $users;
public function __construct() {
$this->users = User::all();
$this->middleware('auth');
}
public function index()
{
return view('admin.index');
}
public function showUsers()
{
$users = $this->users;
return view('admin.users', compact('users'));
}
}
答案 1 :(得分:1)
您需要在构造函数中初始化$users
:
<?php
public $users;
public function __construct() {
$this->middleware('auth');
$this->users = User::all();
}