Skip to content

Commit

Permalink
Merge pull request #2 from jonspark/feature/scopes
Browse files Browse the repository at this point in the history
Adding Query Scopes
  • Loading branch information
jamesmills authored May 4, 2017
2 parents c5accc2 + 5f5c867 commit 44c2050
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 2 deletions.
47 changes: 45 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ composer require jamesmills/eloquent-uuid

In order to use this trait, your **schema** must be something like:

```
```php
<?php
// ...
Schema::create('users', function (Blueprint $table) {
Expand All @@ -29,7 +29,7 @@ In order to use this trait, your **schema** must be something like:

In order to use this in your models, just put `use HasUuidTrait;`:

```
```php
<?php

namespace App;
Expand All @@ -40,3 +40,46 @@ class User extends Eloquent
use HasUuidTrait;
}
```

#### Querying your models

You may use the `findByUuidOrFail` method to try and fetch a model directly:

```php
<?php

Route::get('/user/{uuid}', function($uuid) {
try {
return App\User::findByUuidOrFail($uuid);
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
abort(404);
}
});
```

You may also use the `withUuid` and `withUuids` local query scopes with the query builder.

```php
<?php

Route::get('/user/{uuid}', function($uuid) {
$user = App\User::withUuid($uuid)->first();
if (! $user) {
// Do something else...
}
});
```
```php
<?php

Route::delete('/users', function(Request $request) {
// Receive an array of UUIDs
$uuids = $request->input('uuids');

// Try to get the Users
$users = App\User::withUuids($uuids)->all();

// Handle the delete and return
$users->delete();
});
```
24 changes: 24 additions & 0 deletions src/HasUuidTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,28 @@ public static function findByUuidOrFail($uuid)
{
return self::whereUuid($uuid)->firstOrFail();
}

/**
* Eloquent scope to look for a given UUID
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param String $uuid The UUID to search for
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithUuid($query, $uuid)
{
return $query->where('uuid', $uuid);
}

/**
* Eloquent scope to look for multiple given UUIDs
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param Array $uuids The UUIDs to search for
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWithUuids($query, Array $uuids)
{
return $query->whereIn('uuid', $uuids);
}
}

0 comments on commit 44c2050

Please # to comment.