Neeraj1005
2 months ago
554
14
Laravel

BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Builder::getMedia()

Posted 2 months ago by Neeraj1005

This is my controller index method

   public function index()
    {
        $query = Post::query()->getMedia('posts');

        if(auth()->user()->hasRole('superadmin')) {
            $allPosts = $query->has('user')->latest()->get();

        } elseif (auth()->user()->hasRole('admin')) {
            $allPosts = $query->whereHas('user', function($query){
                $query->where('user_id','!=',1);
            })->latest()->get();

        } else {
            $allPosts = $query->whereHas('user', function($query){
                $query->where('user_id',auth()->user()->id);
            })->latest()->get();
        }
        return view('cms.posts.index',compact('allPosts'));
    }

This is my store method for medialib

   public function store(PostStoreRequest $request)
    {
        $input = $request->validated();
        // dd($input);
        $posts = auth()->user()->posts()->create($input);

        $posts->tags()->attach(request('tags'));

        if($request->hasFile('featuredimage')){

            $posts->addMedia($request->featuredimage)
                    ->toMediaCollection('posts');

        }

        return redirect(route('posts.index'))->withMessage('post 😊 created successfully');
    }

WHERE DID MAKE A MISTAKE OR SOMETHING DID I WRONG?

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