0

I am adding data to mongoDb using laravel :

In Model: Banner.php

<?php

namespace App\Models\Mongo;

use Illuminate\Database\Eloquent\Model;

class Banner extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'banner';
    protected $guarded = ['_id'];
    public $timestamps = false;
    protected $fillable = [
        '_id',
        'url',
        'width',
        'height',
    ];
}

In Controller : BannerController.php

use App\Models\Mongo\Banner;
use MongoDB\BSON\ObjectId;
public function store(Request $request)
{
   Banner::create([
     '_id'   => new ObjectId(),
     'url'   => 'test.jpg',
     'width' => 960,
     'height'=> 300
   ]);
   return response()->json([
        'status' => 'success'
    ], 200);
}

ERROR : message: "Call to a member function prepare() on null"

Or I tried another way, instead of saving with model class I use Repositories : BannerRepository.php:

<?php
namespace App\Repositories\MongoDB;
use App\Models\Mongo\Banner;
use MongoDB\BSON\ObjectId;
class BannerRepository extends MongoDBBaseRepository
{
    public function model()
    {
        return Banner::class;
    }
}

In controller :

use App\Models\Mongo\Banner;
use App\Repositories\MongoDB\BannerRepository;
use MongoDB\BSON\ObjectId;

   /**
     * @var BannerRepository
     */
   protected $bannerRepository;

public function __construct(
        BannerRepository $bannerRepository
 ) {
        $this->bannerRepository = $bannerRepository;
}
public function store(Request $request)
{
   $this->bannerRepository->getModel()->create([
     '_id'   => new ObjectId(),
     'url'   => 'test.jpg',
     'width' => 960,
     'height'=> 300
   ]);
   return response()->json([
        'status' => 'success'
    ], 200);
}

ERROR : Return value of App\\Repositories\\MongoDBBaseRepository::getModel() must be an instance of Jenssegers\\Mongodb\\Eloquent\\Model, instance of App\\Models\\Mongo\\Banner returned"

I have tried two ways. And both error. Don't know where I did wrong. Please give me your opinion. I'm new to laravel so it's a bit difficult. Thank you

1 Answer 1

1

Your model is extending Illuminate\Database\Eloquent\Model;

Try to use Mongo Jenssegers\Mongodb\Eloquent\Model;

Something like this:

<?php

namespace App\Models\Mongo;

use Jenssegers\Mongodb\Eloquent\Model;

class Banner extends Model
{
}

You can find more information here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you..This is a good answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.