I would like to know if there is any other way than to repeat my request in my controller. I have a function show($slug)
with a query inside that takes the variable $teacher
.
protected function show($slug)
{
$teacher = Teacher::where('slug', $slug)->firstOrFail();
return view('posts.postTeacher', [
'teacher' => $teacher,
'imageProfile' => $this->getImageProfile($slug)
]);
}
I created another function to manage my image. Only, I don't know how to access the varialbe $teacher of the other method. Then I am obliged to create a new one with the $slug too.
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;
}
Is there a better way to do this?
Why not just move getImageProfile
inside Teacher
-class?
class Teacher extends Model {
// ....
public function getImageProfile()
{
$basePath = 'uploads/teachers/';
$fullname = pathinfo($this->picture, PATHINFO_FILENAME);
return $basePath . $fullname . '_profile.jpg';
}
}
and
protected function show($slug) {
$teacher = Teacher::where('slug', $slug)->firstOrFail();
return view('posts.postTeacher', [
'teacher' => $teacher,
'imageProfile' => $teacher->getImageProfile()
]);
}
Grouping logical things together, make the usage easier
Your second method could take the $fullname
as an input argument:
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;
}
You should be able to do this with Route-Model Binding (as described here). You can add a method to your teacher model that specifies that you're using a slug (instead of an id, which is the default):
public function getRouteKeyName()
{
return 'slug';
}
With this you can setup your routes to look for the slug and pull up the appropriate instance of the teacher model for use in your controller methods.
// in your routes file
Route::get('teachers/{teacher}', 'TeachersController@show');
// 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;
}