我对laravel有点新意并尝试做一件简单的事情,只是尝试用雄辩的方式选择多行并尝试:
<?php
namespace App\Http\Controllers;
use Auth;
use App\Company;
use App\User;
use Illuminate\Support\Facades\View;
use Model;
class BaseController extends Controller {
public function __construct() {
//$companies = Company::find(1);
//$companies = Company::all();
$companies = Company::where('owner_id', Auth::user()->id);
print_r($cpm);
View::share ( 'companies', '$companies' );
}
}
但总是得到这个错误:
ErrorException
尝试在BaseController.php中获取非对象的属性(第16行)
以上2条注释行正常,所以我有点迷失了?
谢谢,
尼古拉斯
答案 0 :(得分:2)
public function __construct() {
//$companies = Company::find(1);
//$companies = Company::all();
$companies = Company::where('owner_id', Auth::user()->id);
print_r($cpm);
View::share ( 'companies', '$companies' );
}
这篇文章:
$companies = Company::where('owner_id', Auth::user()->id);
需要改变这个:
$companies = Company::where('owner_id', Auth::user()->id)->get();
get确保你的sql被运行,输出我们返回到$ companies。
我相信
View::share ( 'companies', '$companies' );
需要:
View::share ( 'companies', $companies );
导致:
public function __construct() {
//$companies = Company::find(1);
//$companies = Company::all();
$companies = Company::where('owner_id', Auth::user()->id)->get();
print_r($cpm);
View::share ( 'companies', $companies );
}
答案 1 :(得分:1)
您正在尝试在没有用户登录时获取已登录用户的ID。因此您应该检查用户是否已登录。
我建议您使用middleware。
您还可以使用以下方法检查用户是否已登录:
if (Auth::check()) {
$companies = Company::where('owner_id', Auth::user()->id)->get();
}
阅读本文以获取有关身份验证的更多信息:https://laravel.com/docs/5.6/authentication
答案 2 :(得分:0)
where()
方法返回Builder对象,而不是查询结果。您需要致电get()
method以获得可利用的收藏品。