Sabonzy
134
3
Laravel

Metthod on Models returned null when called when using getter and setter

Posted 1 year ago by Sabonzy

this is the Model class

class Post extends Model{
     protected $routeName;
 
        public function setNamedRoute($route)
          {
              $this->routeName = $route;

          }

        public function getNamedRoute($params = [])
          {
        //  $this->routeName is always null
            return route($this->routeName, $params); 
          }
}

this is the controller

class PostsController extends Controller{

 private $posts;

        public function __construct(PostRepository $posts)
        {
            $this->posts = $posts;
        }

        public function index()
        {           
            $posts->setNamedRoute('posts.index');
            
            return $applicants = PostsResource::collection(
                $this->posts->withCriteria(
                    [
                        new HasRelation('comments'),
                    ])->all()
            );
            
        }
   }

in the PostsResource class

 class PostsResource extends JsonResource
    {
        
        public function toArray($request)
        {
            return [
                "id"                    => $this->id,
                "title"             => $this->title,
                "body"          => $this->body,
                
                "comments"              => CommentsResource::collection($this->whenLoaded('comments')),

                "route"                 => $this->getNamedRoute(['comment' => $this->id]), // this return null all the time
            ];
        }
    }

how do i get the value assigned to the $this->routeName to be available when the method getNamedRoute() is called. i have tried it with the Accessors & Mutators and the same happens

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.