E
E
Evgeniy Golovin2021-12-28 00:46:10
Laravel
Evgeniy Golovin, 2021-12-28 00:46:10

How to call a model method in Laravel?

I continue to learn Laravel. I work with resources.

  • There is a model, a controller, an Initial resource (the first start for the site)
  • There is a model, controller, resource Categoty (site categories)


In InitialResource I write
public function toArray($request) {
        return [
            'mainMenu'   => CategoryResource::collection(Category::all()),
            'navigation' => '',
            'cities'     => '',
            'status'     => 'success',
        ];
    }

Everything works fine, but it displays all categories, not active ones.

Created a method in the Category model
public function index() {
        return $this->where('actf', 1)->get();
}

Next, I edit the resource
public function toArray($request) {
        return [
            'mainMenu'   => CategoryResource::collection([Category::class, 'index']),
            'navigation' => 2,
            'cities'     => 3,
            'status'     => 'success',
        ];
    }

And it doesn't work. Shouts that he does not get a title

In the category resource, he is needed
public function toArray($request) {
        return [
            'title' => $this->title,
            'url'   => '/catalog/' . $this->url,
        ];
    }

Point to the right path. What am I calling wrong?
Of course, you can create new Category () in InitialResource and call the index () method, but I feel that this is not correct.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2021-12-28
@delphinpro

Well, if you ask for everything Category::all(), then everything is spit out for you.
Request only active

'mainMenu'   => CategoryResource::collection(Category::where('enabled', true)->get()),

https://laravel.com/docs/8.x/eloquent#building-queries

J
jazzus, 2021-12-28
@jazzus

Delete initial. Delete InitialResource. Because it is not a resource. Pass data via json response. Inside which CategoryResource. For the correct request, the Query Builder uses the where method. If you want to call a method from the model, do scope. Without get in the model. Pass as written in the documentation
CategoryResource::collection($categories);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question