Coder Social home page Coder Social logo

bosnadev / repository Goto Github PK

View Code? Open in Web Editor NEW
821.0 59.0 232.0 118 KB

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

PHP 100.00%
laravel php laravel-repositories criteria database-layer

repository's People

Contributors

casperlaitw avatar jdsingh avatar maartenpaauw avatar miclf avatar mirzap avatar petehouston avatar thangngoc89 avatar willianmano avatar wink- avatar xcaptain avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

repository's Issues

Get Model From Controller

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

Call to undefined method findWhere

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';
}

}

update() method does not work.

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);
}

Repository::pushCriteria() does not exist on this mock object

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);
}

Eager Loading

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!

Unable Create Record With Beanstalkd Queue

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

Updates do not trigger Eloquent Events

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);
    }

should i use model's method directly in controller ?

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?

Support for withTrashed() and onlyTrashed() ?

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?

update fails fillable

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!!!

bug in vendor:publish

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 ../

New branch - refactor

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.

where concat

Hi, how can I do a findwhere with concat
something like

select * from TABLE where concat( name, lastname, email ) like %misearch%

Repository testing Fails

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

Use criteria with IoC

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.

How can I get ordered resultset in child repository?

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?

Call to undefined method Illuminate\Database\Query\Builder::sync()

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

findWhere after Criteria

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)

In a loop, repository always returns me the same record

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 !

Usage question

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

Why should I provide ID to delete?

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.

Readme

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

artisan command?

what I need to configure to use the artisan commands

php artisan make:repository?

How can we use other methods traditionally available in the model?

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!

Criteria stay applied for the next query

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 ?

Paginate method returns a collection

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?

Create method doesn't work

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

findWhere method does not work when resetScope(true) is called

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

  1. @appkr has implemented findWhere with orWhere
    https://github.com/appkr/Repositories/blob/refactor/src/Eloquent/Repository.php#L225
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);
            }
        }

Multiple Criteria in Controller method

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?

Failed on Unit Testing

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

Caching Features

Hello!

It it possible to implement caching features in the select queries ?

Greetings.

It doesn't work in lumen5.1. Target [App\\Http\\Controllers\\Api\\V1\\UserController] is not instantiable.

// 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.

Call to undefined method findAllBy()

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()

What's the proper way to create criteria with pivot tables?

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 create a model through repository

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.