PHP code example of dannyweeks / laravel-base-repository
1. Go to this page and download the library: Download dannyweeks/laravel-base-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/ */
dannyweeks / laravel-base-repository example snippets
$repo = new App\Repositories\PostRepository();
var_dump($repo->getById(1)); // Returns the Post with an ID of 1.
var_dump($repo->getAll()); // Returns a collection of all your posts.
namespace App\Models;
class Post extends Illuminate\Database\Eloquent\Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
public function author()
{
return $this->hasOne('App\Models\User');
}
}
namespace App\Repositories;
use Weeks\Laravel\Repositories\BaseEloquentRepository;
class PostRepository extends BaseEloquentRepository
{
protected $model = App\Models\Post::class;
protected $relationships = ['comments', 'author'];
}
namespace App\Http\Controllers;
use App\Repositories\PostRepository;
class PostController extends Controller
{
protected $posts;
public function __construct(PostRepository $posts)
{
$this->posts = $posts;
}
public function show($id)
{
// get the post and eagerly load the comments for it too.
$post = $this->posts->with('comments')->getById($id);
return view('posts.show', compact('post'));
}
}
namespace App\Repositories;
use Weeks\Laravel\Repositories\BaseEloquentRepository;
use Weeks\Laravel\Repositories\Traits\ThrowsHttpExceptions;
class PostRepository extends BaseEloquentRepository
{
use ThrowsHttpExceptions;
protected $model = App\Models\Post::class;
}
$posts = new PostRepository();
$post = $posts->disableHttpExceptions()->getById(1000); // returns null rather than throwing a 404 error.
namespace App\Repositories;
use Weeks\Laravel\Repositories\BaseEloquentRepository;
use Weeks\Laravel\Repositories\Traits\CacheResults;
class PostRepository extends BaseEloquentRepository
{
use CacheResults;
protected $model = App\Models\Post::class;
protected $relationships = ['comments', 'author'];
protected $nonCacheableMethods = ['getById'];
protected $cacheTtl = 30;
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.