N
N
NiksevenEleven2022-02-16 10:38:51
Laravel
NiksevenEleven, 2022-02-16 10:38:51

How to make a multiple request giving posts tied to Laravel cities?

Please tell me, I have models: City, Posts, Post_Cities.
I need to make a request through a multiple select to get an array and then process it in the controller and give posts tied to a specific city.

After request from the form I get

+query: Symfony\Component\HttpFoundation\InputBag {#529 ▼
    #parameters: array:1 [▼
      "cities" => array:2 [▼
        0 => "9"
        1 => "10"
      ]
    ]
  }


City model
public function posts()
    {
        return  $this->belongsToMany(Post::class,'post_cities','city_id','post_id');

    }


Post Model
public function cities()
    {
        return  $this->belongsToMany(City::class,'post_cities','post_id','city_id');

    }


How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2022-02-16
@delphinpro

City:find([9, 10])->with('posts')->get()
City::with('posts')->find([9, 10])
Something like this.

W
workaandrey, 2022-02-16
@workaandrey

$citiesIds = $request->input('cities');
Posts::query()
    ->whereHas('cities', function($query) use($citiesIds) {
        return $query->whereIn('id', $citiesIds);
    })
    ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question