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
CodePudding user response:
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.