PHP code example of pp-spaces / laravel-repository
1. Go to this page and download the library: Download pp-spaces/laravel-repository library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
pp-spaces / laravel-repository example snippets
namespace App\Http\Repositories;
use PPSpaces\Repositories\Repository;
class UserRepository extends Repository {
/**
* The user model instance.
*
* @var \App\User
*/
protected $model = "App\User";
/**
* Scope a query for the model before executing
*
* @param \Illuminate\Database\Query\Builder $query
* @return void
*/
public function before($query) {
$query->role('staff');
}
/**
* Get all of the models from the database.
*
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function get($columns = ['*']) {
$users = $this->repository
->active()
->orderBy('updated_at', 'DESC')
->get();
return $users;
}
}
use App\Http\Repositories\UserRepository;
class UserController extends Controller
{
protected $users;
public function __construct(UserRepository $users)
{
$this->users = $users;
}
public function index()
{
return $this->users->get();
}
}
public function index(UserRepository $user)
{
return $user->get();
}
public function show(UserRepository $user)
{
// Authorizing the repository model
// Check https://laravel.com/docs/master/authorization
$this->authorize('view', $user->model());
// This $user will resolved by the id provided by the router
// e.g. /api/user/1
// $user will be the result of $user->id === 1
return $user;
}
sh
php artisan make:repository UserRepository
sh
php artisan make:repository UserRepository --model=User
sh
php artisan make:repository UserRepository --model=User
diff
namespace App\Http\Repositories;
- use App\User;
- use PPSpaces\Repositories\Model as Repository;
+ use PPSpaces\Repositories\Repository;
class UserRepository extends Repository {
+ /**
+ * The user model instance.
+ *
+ * @var \App\User
+ */
+ protected $model = "App\User";
- protected $user;
- public function __construct(User $user) {
- $this->user = $user;
- }
public function index()
{
// `$this->users->all()` will always resolved the same result as `$this->users->get()`
- return $this->users->all();
+ return $this->users->get();
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.