0

我尝试检索我的用户的头像,当他登录我的应用程序。检索与身份验证和多态关系的头像用户

实际上,对于最佳实践,我使用图像表的多态关系。

我的图像表看起来像。

Schema::create('images', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->string('path'); 
     $table->string('alt'); 
     $table->string('title'); 
     $table->string('link'); 
     $table->integer('imageable_id'); 
     $table->string('imageable_type'); 
     $table->timestamps(); 
    }); 

我的路径与我的头像和imageable_id user_id关系和imageable_type关联的模型(用户)有关。

但是,当我检查,如果用户登录,并尝试后,我的目标与

@if(Auth::user()->image) 
<img alt="" src="{{????????}}"> 
@endif 

在我的模型用户访问我有我的关系就像

public function image(){ 
    return $this->morphMany('Image','imageable'); 
} 

如何访问我),我与验证的用户图像的路径::用户( - >图像

感谢

回答

1

由于MO rphMany()允许的多个关系,还是先重命名)的方法进行的图像(:

public function images() 
{ 
    return $this->morphMany('App\Image','imageable'); 
} 

然后,我将创建用户模型的另一种方法,例如defaultImage(),这意味着所述第一图像:

public function defaultImage() 
{ 
    return $this->images()->first(); 
} 

然后,在你的模板将成为:

@if(!is_empty(Auth::user()->defaultImage())) 
    <img alt="" src="{{ Auth::user()->defaultImage()->path }}"> 
@endif