2017-05-08 39 views
1

我想知道是否有任何其他的办法,而不是重复我的要求我的控制器。我有一个查询功能show($slug)内,是以可变$teacher如何从另一种方法访问变量?或者如何做得更好?

protected function show($slug) 
{ 
    $teacher = Teacher::where('slug', $slug)->firstOrFail(); 

    return view('posts.postTeacher', [ 
     'teacher' => $teacher, 
     'imageProfile' => $this->getImageProfile($slug) 
    ]); 
} 

我创建了另一个函数来管理我的图像。只有,我不知道如何访问其他方法的varialbe $老师。然后我有义务用$ slug创建一个新的。

public function getImageProfile($slug) 
{ 
    $teacher = Teacher::where('slug', $slug)->firstOrFail(); 

    $basePath = 'uploads/teachers/'; 
    $fullname = pathinfo($teacher->picture, PATHINFO_FILENAME); 
    $imageProfile = $basePath . $fullname . '_profile.jpg'; 

    return $imageProfile; 
} 

有没有更好的方法来做到这一点?

+0

除了'$ slug'之外,你不能''teacher'作为参数传递给'getImageProfile()'吗?或代替'$ slug'--你不告诉你的代码中使用它。 – alexis

回答

3

为什么不只是移动getImageProfileTeacher -class?

class Teacher extends Model { 

    // .... 

    public function getImageProfile() 
    { 
     $basePath = 'uploads/teachers/'; 
     $fullname = pathinfo($this->picture, PATHINFO_FILENAME); 
     return $basePath . $fullname . '_profile.jpg'; 
    } 

} 

protected function show($slug) { 
    $teacher = Teacher::where('slug', $slug)->firstOrFail(); 

    return view('posts.postTeacher', [ 
     'teacher' => $teacher, 
     'imageProfile' => $teacher->getImageProfile() 
    ]); 
} 

分组逻辑的东西放在一起,让使用更方便

+0

非常感谢!您的解决方案有效,非常理想。我没有想到这样做,现在我不会再忘记它了。谢谢 ! – Jeremy

1

你的第二个方法可以采取$fullname作为输入参数:

protected function show($slug) 
{ 
    $teacher = Teacher::where('slug', $slug)->firstOrFail(); 
    $fullname = pathinfo($teacher->picture, PATHINFO_FILENAME); 

    return view('posts.postTeacher', [ 
     'teacher' => $teacher, 
     'imageProfile' => $this->getImageProfile($slug, $fullname) 
    ]); 
} 

public function getImageProfile($slug, $profilePrefix) 
{ 
    $basePath = 'uploads/teachers/'; 
    $imageProfile = $basePath . $profilePrefix . '_profile.jpg'; 

    return $imageProfile; 
} 
+0

@ Philipp上面的回答也可以,而且绝对清洁。 – khan

1

你应该能够与路由的模型绑定(如描述here)来做到这一点。您可以将方法添加到您的老师模型,指定要使用蛞蝓(而不是一个ID,这是默认):

public function getRouteKeyName() 
{ 
    return 'slug'; 
} 

有了这个,你可以设置你的路由来寻找鼻涕虫拉出适合您的控制器方法的教师模型实例。

// in your routes file 
Route::get('teachers/{teacher}', '[email protected]'); 

// in your controller 
protected function show(Teacher $teacher) 
{ 
    $imageProfile = $teacher->getImageProfile(); 
    return view('posts.postTeacher', compact('teacher', 'imageProfile')); 
} 

// in model 
public function getImageProfile() 
{ 
    $basePath = 'uploads/teachers/'; 
    $fullname = pathinfo($this->picture, PATHINFO_FILENAME); 
    $imageProfile = $basePath . $fullname . '_profile.jpg'; 

    return $imageProfile; 
} 
相关问题