bosnadev / repository Goto Github PK
View Code? Open in Web Editor NEWLaravel Repositories is a package for Laravel 5 which is used to abstract the database layer. This makes applications much easier to maintain.
Home Page: https://bosnadev.com
Laravel Repositories is a package for Laravel 5 which is used to abstract the database layer. This makes applications much easier to maintain.
Home Page: https://bosnadev.com
I am using the updateRich method and was wondering if there is a way to get the model that is created from it? I am wanting to send the model back to my view after the save completes. I took a look at the source code and it does not seem like the model is exposed. Please let me know if you have any suggestions?
Thanks,
Paul
I am getting the above message and I don't know what I am doing wrong.
I am calling the findWhere method from a view composer. Here is my code
use Eventsapp\Repositories\SectionRepository;
use Eventsapp\Repositories\PageRepository;
use Eventsapp\Repositories\PostRepository;
class OnePageComposer{
protected $postsRepo, $pagesRepo, $sectionsRepo;
public function __construct(
PageRepository $pagesRepo,
SectionRepository $sectionsRepo,
PostRepository $postsRepo,
)
{
$this->sectionsRepo = $sectionsRepo;
$this->pagesRepo = $pagesRepo;
$this->postsRepo = $postsRepo;
}
public function compose($view){
$view->with([
'sections' => $this->sectionsRepo->findWhere(['status'=>1]),
'homepage' => $this->pagesRepo->getHomepage()
]);
}
}
My SectionRepository looks like this:
use Bosnadev\Repositories\Contracts\RepositoryInterface;
use Bosnadev\Repositories\Eloquent\Repository;
class SectionRepository extends Repository{
public function model() {
return 'App\Models\Section';
}
}
Similarly Scope, can be made Global Scope
The updata() method does not work. It seems that you missed the first() after where() The where() return an array but not an unique model.
public function update(array $data, $id, $attribute="id") {
return $this->model->where($attribute, '=', $id)->update($data);
}
Running tests got this error:
BadMethodCallException: Method Mockery_0_App_Repositories_ProductRepository::pushCriteria() does not exist on this mock object
Making mock like that
$this->productRepository = \Mockery::mock('App\Repositories\ProductRepository');
In the same time
$this->productRepository->shouldReceive('paginate')
doesn't give errors
More code:
public function setUp()
{
parent::setUp();
$this->productRepository = m::mock('App\Repositories\ProductRepository');
$this->variantRepository = m::mock('App\Repositories\VariantRepository');
$this->request = m::mock('Illuminate\Http\Request');
$this->productController = new \App\Http\Controllers\Admin\ProductController($this->productRepository, $this->variantRepository);
}
public function tearDown()
{
m::close();
parent::tearDown();
}
public function testIndex()
{
$this->productRepository->shouldReceive('paginate')->once()->andReturn(array());
$response = $this->productController->getIndex($this->request);
$this->assertEqual(array(), $response);
}
When i run a test to test the controller class that issues arise.How to get ride of that.Here is my test class
Are there any plans to extend this package to include the Eager Loading functionality in Repositories described here?
[https://bosnadev.com/2015/03/26/using-repository-pattern-in-laravel-5-eloquent-relations-and-eager-loading/]
Thanks!
as title :)
Thanks
Hi
do you ever face problem that you cant insert/create any record when queue driver set as beanstalkd
?
i always got
Trying to get property of non-object
Seems like $this->model
got undefined and error above got triggered when execute this line
return $this->model->create($data);
my code is pretty simple
<?php
// controller
$this->dispatch(
new \Modules\Accounting\Jobs\HitungAdministrasiSimpanan('fa108a98-cd89-402e-b60f-bb1b039c2606')
);
// job
$transactionRepository = app()->make(TransactionRepository::class);
// .. rest code ...
$transactionRepository->create([
'reference' => 'SLUG',
'nominal' => 0,
'description' => 'BLANK',
]);
But when queue driver back to sync
then everything is ok ..
Any idea?
Thanks
Using the update call in this repository does not trigger an updated Eloquent event.
Current code for said function
public function update(array $data, $id, $attribute="id") {
return $this->model->where($attribute, '=', $id)->update($data);
}
To fix it, should be something like this:
public function update(array $data, $id, $attribute="id") {
return $this->model->where($attribute, '=', $id)->first()->update($data);
}
copy from other website's comment
With this approach, is it ok for the controller to call methods on the Model, so if you call find($id) and get back an instance of an FAQ - what should the controller be allowed and not allowed to do with that FAQ object? If say, the FAQ has a related entity set up as an Eloquent 'hasMany', can we access this directly? Or should some things be only going through calls on the repository?
I'm using SoftDeletes on my model and if I try to query trashed models it doesn't seem to work.
First I've tried this:
$item = $itemRepo->withTrashed()->all();
It says there is no method withTrashed()
on my repository. Then I tried to make criteria:
...
public function apply($model, Repository $repository) {
return $model->withTrashed();
}
...
...but it says there is no method withTrashed()
on Builder class. It seems $model
here is the query builder, not the model itself.
Same goes for onlyTrashed()
. Is there any way to use these methods with your Repository package?
If I do a update passing a data array with request->all() it not takes fillable
I change the update method adding ->first like this:
public function update(array $data, $id, $attribute = "id")
{
return $this->model->where($attribute, '=', $id)->first()->update($data);
}
it works!!!
Failed opening requi
red '/Users/cyberneticist/www/sites/watchprice/backend/vendor/bosnadev/repo
sitories/src/Bosnadev/Repositories/Providers/../../../config/repositories.p
hp
you've forgot to add one more ../
Hey! @bosnadev
Last couple of days I've been playing around with your package and made some modification for my personal project. Since I made too much change to your package after forking (this includes api change, and this will break your users' code), I think pull request is not appropriate. But if you happen to like even a small part of my work, you can merge them. Thanks for the great package.
https://github.com/appkr/Repositories/tree/refactor
With best wishes,
Appkr.
Hi, how can I do a findwhere with concat
something like
select * from TABLE where concat( name, lastname, email ) like %misearch%
When i run a test to test the controller class below issues arise.
ErrorException: Argument 1 passed to Bosnadev\Repositories\Eloquent\Repository::__construct() must be an instance of Illuminate\Container\Container, none given, called in
How to get ride of that.Here is my test class
Is it right?
Hi, can I use doing this
$x = new App\Repositories\MyRepository
without injection at construct??
Hi,
I would like to know if it's possible to use IoC in criteria ? For example in my criteria I want to use Guard for replace the data in where clause
public function apply( $model, Repository $repository )
{
$model = $model->where(function($query){
$query->where('level', '<=', 10); // Replace 10 by data in user relationships
$query->orWhere('level', '<=', 5); // Replace 5 by data in user relationships
});
return $model;
}
Thx.
In my child repository...
class ChildRepository extends \Bosnadev\Repositories\Eloquent\Repository
{
public function model() {}
public function suggest($column, $search)
{
return $this->getByCriteria(new Like($column, $search))
->all(['id', \DB::raw("{$column} as name")]);
}
}
all() returns EloquentCollection, and does not allow additional method chaining.
Before extending this package it was,
public function suggest($column, $query)
{
return $this->model->where($column, 'like', $query . '%')
->orderBy($column, 'asc')->get(['id', \DB::raw("{$column} as name")]);
}
What is the best way I can chain orderBy() with \Bosnadev\Repositories\Eloquent\Repository
. Do I have to make a OrderBy
Criteria?
Hi.. i have code like this where attachments
is morphMany
$update = $this->repository->updateRich($input, $id);
$update->attachments()->sync($attachmentIds);
But its throws Call to undefined method Illuminate\Database\Query\Builder::sync()
Seems like its should return an instance of Illuminate \ Database \ Eloquent \ Model
Any idea?
Thanks
I'm using mongoDB as database and https://github.com/jenssegers/laravel-mongodb package.
When I run this code $this->user->update($request->all(), $id);
, it executes fine but the data is not being updated in database.
Version info
"laravel/framework": "5.0.*",
"jenssegers/mongodb": "~2.1",
I'm doing a criteria before a query like:
$all = $this->repo->findWhere(['status_id'=> $status->id, 'user_id'=> 1])->count();
my criteria is like this:
public function apply($model, Repository $repository)
{
$users = User::filtered()->lists('id')->toArray();
$model = $model->where('user_id', $users);
return $model;
}
the result of criteria is correct, but when I do the findWhere after it returns 0 (and should be return more)
Hi,
I'm facing a weird problem when fetching records from the DB using the find or findWhere methods.
$offersToInsert is an array of objects sent via AJAX.
[
{
id: 2,
title: "red",
type: "tag",
inDB: 1
},
{
id: null,
title: "green",
type: "tag",
inDB: 0
},
{
id: 3,
title: "Simon's",
type: "brand",
inDB: 1
}
];
For each offer in the array, if "inDB" is true, I retrieve the the corresponding tag from the DB.
This is where the problem occurs:
$tag = $this->tagRepo->find($tagData['id']);
Although I've made sure the $tagData['id'] value is different on each iteration, this line always returns
me the same record (the first one it retrieved when processing the first iteration in the loop).
But if I change the "find" method in my TagRepository from this:
/**
* @param $id
* @param array $columns
* @return mixed
*/
public function find($id, $columns = array('*')) {
$this->applyCriteria();
$this->newQuery()->eagerLoadRelations();
return $this->model->find($id, $columns);
}
to this (by removing the newQuery():
/**
* @param $id
* @param array $columns
* @return mixed
*/
public function find($id, $columns = array('*')) {
$this->applyCriteria();
$this->eagerLoadRelations();
return $this->model->find($id, $columns);
}
it works perfectly (even though it might create some effects somewhere ?)
If I directly call the model it works just fine but defeats the purpose of a repository.
$tag = Tag::find($tagData['id']);
Here is the (simplified) code I have in a Job class.
public function __construct($offersToInsert)
{
$this->offersToInsert = $offersToInsert;
}
public function handle(TagRepository $tagRepo)
{
$this->tagRepo = $tagRepo;
$insertedOffers = [];
foreach ($this->offersToInsert as $key => $offer) {
$tagsToBeAttached = [];
foreach ($offer['tags'] as $key => $tagData) {
if($tagData['inDB'] === 0) {
$existingTag = $this->tagRepo
->findWhere([
'title_fr' => $tagData['title'],
'title_en' => $tagData['title']
],
['id', 'counter'],
true
)
->all();
if($existingTag) {
$existingTag[0]->increment('counter');
$tagsToBeAttached[] = $existingTag[0]->id;
}
else {
$newTag = [
'tag_type_id' => 1,
'title_en' => $tagData['title'],
'title_fr' => $tagData['title'],
'counter' => 1,
];
$newTag = $this->tagRepo->create($newTag);
$tagsToBeAttached[] = $newTag->id;
}
}
else {
// Works if I remove the "newQuery()" call inside the "find" method of the repo.
$tag = $this->tagRepo->find($tagData['id']);
// Works just fine.
//$tag = Tag::find($tagData['id']);
}
}
}
// Return whatever...
}
I'm not really familiar with the purpose of the newQuery method, but does someone see something wrong in my code ? Can I safely remove the newQuery() calls everywhere ?
Thanks a lot for your precious time !
the create method in Illuminate\Database\Query\Builder has changed to "insert", the create method should be renamed accordingly
Hey there,
Thanks for your awesome library, I have a question, hopefully not a bug, I am probably not using it right....
Using your example in the README, in the FilmsController
, after you perform a search such as:
$filmsToDelete = $this->film->pushCriteria(new FilmCreatedBefore($search_date))->all();
The element $this->film->model
changes from a instance of Film
model to an instance of Illuminate\Database\Eloquent\Builder
, this in turns makes it impossible to call the RepositoryInterface
functions such as in:
foreach( $filmsToDelete as $f) {
$this->film->delete($f->id);
}
This fails with Call to undefined method Illuminate\Database\Query\Builder::destroy()
as the Repository.php
calls $this->model->destroy($id);
on line 126, but since the model
is not a model anymore it fails.
Is this the expected behaviour or am I doing something wrong?
Thanks.
/S
I was reading the code and I'm a bit confused, why should I provide the id to delete while I have it in the instance it self, that means that a any model instance can delete any other record.
Hi, i would like to use your package, could you perhaps write something in the readme about how i can integrate it? it seems you extend eloquent and such but do you entirely discard eloquent models?
Thanks
what I need to configure to use the artisan commands
php artisan make:repository?
as title :)
I want to use whereIn orderBy...
Can you give an example?
Thanks
Say I have this code:
use App\Repositories\TestsRepo as Test;
public function show($reference_number, Test $test){
return $shipment->findBy( 'reference_number', $reference_number );
}
Now what if I need to apply other eloquent methods? Such as ->where('field', 'value'); or order_by
I know the order_by is not relevant in this example, but there are tons of other eloquent methods that I'm not able to chain.
Thanks!
The method has been deprecated in 5.3 and replaced with pluck
"The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same."
I need to retrieve two collections from the same repository, but when pushgin criterias they stay applied to the repository for the next query :
$elements = $this->elementRepository->pushCriteria(new ElementByElementTypeCriteria(1)->paginate(7);
// the Criteria stay applied for the next call to paginate() on the same repo
$elements_type = $this->elementRepository->pushCriteria(new ElementByElementTypeCriteria(6))->paginate(3);
What is the good approach to do that ?
Hi,
Thank you for the awesome package.
I'm wondering why the paginate()
method return a Collection instance instead of a Illuminate\Pagination\Paginator
instance?
If you also think it'd be a great idea, I can work on a PR
When I try to use the create method, it throws me :
BadMethodCallException in Builder.php line 1990: Call to undefined method Illuminate\Database\Query\Builder::create()
I think it's because the repository stores an instance of Illuminate \ Database \ Eloquent \ Builder instead Illuminate \ Database \ Eloquent \ Model instance
Hi, how can I do a whereIn search?
I did some digging into this issue and found that findWhere
method only works if pushCriteria()
is called before findWhere
.
If resetScope(true)
is called before findWhere
, then the $where condition does not apply.
Possible solutions
foreach($where as $field => $value) {
if(is_array($value)) {
list($field, $condition, $value) = $value;
$this->model = $this->model->where($field,$condition,$value);
} else {
$this->model = $this->model->where($field,'=',$value);
}
}
How to call more then 1 Criteria inside the controller method? For example, I want to get separated active and inactive users (status is checked between 2 tables and a few where clauses).
If I use:
$active = $this->user->getByCriteria(new GetActiveUsers($role_id))->all();
and
$inactive = $this->user->getByCriteria(new GetInactiveUsers($role_id))->all();
the second one just appends Criteria GetInactiveUsers on the above query.
How to reset query data in this example?
Hi,
i try to create some unit test, here is my sample code
<?php
namespace Modules\User\Gateways;
use Modules\Core\Gateways\AbstractGateway;
use Modules\User\Repositories\RoleRepository;
class RoleGateway extends AbstractGateway
{
protected $repository;
public function __construct(RoleRepository $repository)
{
$this->repository = $repository;
}
public function store(Request $request)
{
$input = $request->only('name', 'description');
return $this->repository->create($input);
}
}
and this is my RoleRepository
<?php
namespace Modules\User\Repositories;
use Modules\Core\Repositories\AbstractRepository;
use Modules\User\Models\Role;
class RoleRepository extends AbstractRepository
{
public function model()
{
return Role::class;
}
}
and when i ran phpunit
, i've got this
[2015-11-03 23:35:45] testing.ERROR: exception 'BadMethodCallException' with message 'Call to undefined method Illuminate\Database\Query\Builder::create()' in /home/ferri/Developments/domains/default/public_html/laravel-modular/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2047
Stack trace:
#0 [internal function]: Illuminate\Database\Query\Builder->__call('create', Array)
#1 [internal function]: Illuminate\Database\Query\Builder->create(Array)
Any idea?
Thanks
Hello!
It it possible to implement caching features in the select queries ?
Greetings.
// repository
namespace App\Repositories;
use Bosnadev\Repositories\Contracts\RepositoryInterface;
use Bosnadev\Repositories\Eloquent\Repository;
class UserRepository extends Repository
{
public function model()
{
return 'App\Models\User';
}
}
// controller
class UserController extends BaseController
{
protected $user;
protected function __construct(UserRepository $user)
{
$this->user = $user;
}
public function user()
{
$user = $this->user->all();
return $this->response->item($user, new UserTransformer);
}
}
If I Comment out the repository, and it works.
I have:
use VCN\Repositories\AccountRepository as Account;
and try:
$res = $this->account->findAllBy('type',1);
and I receive this error:
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to undefined method VCN\Repositories\AccountRepository::findAllBy()
Laravel 5.3
$collection = $this->repos->lists('xxx', 'xx')->toArray();
Outputs:
BadMethodCallException in Builder.php line 2448:
Call to undefined method Illuminate\Database\Query\Builder::lists()
This method is depracted since 5.2
https://laravel.com/api/5.2/Illuminate/Database/Query/Builder.html
lists(string $column, string|null $key = null) deprecated
Alias for the "pluck" method.
It has been replaced by pluck
Hello Sir,
I Want To Use Multiple Models For My DashboardRepository So How Can I Achieve This ?
Thank You
I have a table, A, which has a many-to-many relationship with two other tables, B and C, via their respective pivot tables.
My model for A has a method which returns a BelongsToMany relation for table B. How can I use that when I'm building a criteria to find specific results?
Ex: I want to get all of the rows of table A that have a specific value of B in the pivot table
how to use one to many or reverse in a model and apply it to criteria?
for example I want when a user logged in and show only movie that creted by related user
I don't want to use massive assignment, so the default create method doesn't work for me.
I tried to use the traditional way to save a model, but I can't assign attributes to a model because model is protected.
$this->post->model->title = 'test'
$this->post->model->save();
just throw an error.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.