2017-05-08 59 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; 
} 
相關問題