Jeremy Jeremy - 6 months ago 24
PHP Question

How do I access a variable from another method? Or how to do better?

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?

Answer Source

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