我正在努力理解laravel是如何工作的,而且我很难用它来完成
模型 - User.php用户模型
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('email' , 'username' , 'password', 'code');
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
public function Characters()
{
return $this->hasMany('Character');
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
模型 - Character.php角色模型
<?php
class Character extends Eloquent {
protected $table = 'characters';
protected $fillable = array('lord_id','char_name', 'char_dynasty', 'picture');
public function user()
{
return $this->belongsTo('User');
}
public function Titles()
{
return $this->hasMany('Title');
}
}
?>
routes.php文件
Route::group(array('prefix' => 'user'), function()
{
Route::get("/{user}", array(
'as' => 'user-profile',
'uses' => 'ProfileController@user'));
});
ProfileController.php
<?php
class ProfileController extends BaseController{
public function user($user) {
$user = User::where('username', '=', Session::get('theuser') );
$char = DB::table('characters')
->join('users', function($join)
{
$join->on('users.id', '=', 'characters.user_id')
->where('characters.id', '=', 'characters.lord_id');
})
->get();
if($user->count()) {
$user = $user->first();
return View::make('layout.profile')
->with('user', $user)
->with('char', $char);
}
return App::abort(404);
}
}
在我的代码中,我将使用以下内容重定向到此路线:
return Redirect::route('user-profile', Session::get('theuser'));
在视图中我只想做: 欢迎回来,{{$ user-&gt; username}},您的主角是{{$ char-&gt; char_name}}
我的问题是我会收到此错误:尝试在我的视图中获取非对象的属性。我确信它指的是$ char-&gt; char_name。出了什么问题?我很难理解Laravel。我不知道为什么。提前谢谢!
答案 0 :(得分:0)
您应该使用Auth类来获取登录用户的会话信息。
$user = Auth::user();
$welcome_message = "Welcome back, $user->username, your main character is $user->Character->char_name";
您也不需要将任何内容传递给该路线。只需检查用户是否已登录,然后检索数据。您可以从应用程序的任何位置访问此数据。
if (Auth::check())
{
//the user is logged in
$user = Auth::user();
要在评论中回答您的问题,请阅读documentation解决所有这些问题,但是:
public function user()
{
if (Auth::check())
{
$user = Auth::user();
return View::make('rtfm', compact('user'));
}
else
{
return "The documentation explains all of this very clearly.";
}
}