I would like to use the Repository Pattern
but I am stuck on the syntax. I want to get my function index().
First step, I create my folder Repositories
and I create the file AuteurRepository.php
In my file AuteurController I have this:
public function index()
{
$auteurs = Auteur::oldest()->paginate(5);
return view('admin.auteurs.index', compact('auteurs'))
->with('i', (request()->input('page', 1)-1)*5);
}
And in my Model I only have a file Auteur
protected $fillable = ['name', 'firstname'];
I have 2 questions:
1) In my file AuteurRepository how should I create my function index() ?
I have tried this ?
<?php
namespace App\Repositories;
use App\Auteur;
class AuteurRepository
{
public function index()
{
return Auteur::oldest()->paginate(5);
}
}
?>
My second question is in my AuteurController I don't understand what to do ?
I have this for now
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Auteur;
use App\Repositories\AuteurRepository;
class AuteurController extends Controller
{
protected $auteurs;
public function __construct(AuteurRepository $auteurs)
{
$this->auteurs = $auteurs;
}
public function index(Request $request)
{
return view('admin.auteurs.index', compact('auteurs'))
}
}
1) In my file AuteurRepository how should I create my function index()?
You can give it the name what you want, index(), allRecords(), ... . And perform the query you need.
My second question is in my AuteurController I don't understand what to do ?
If your repository looks like this:
class AuteurRepository
{
public function index()
{
return Auteur::oldest()->paginate(5);
}
}
In your controller you can access the repo index function like this:
class AuteurController extends Controller
{
protected $auteurs;
public function __construct(AuteurRepository $auteurs)
{
$this->auteurs = $auteurs;
}
public function index(Request $request)
{
$auteurs = $this->auteurs->index();
return view('admin.auteurs.index', compact('auteurs'))
}
}
EDIT
Also, you can customize a bit the query. For example:
In the repository accept a parameter in the index method:
class AuteurRepository
{
public function index($filters)
{
$pagination = $filters['pagination'];
$order = $filters['order'];
return Auteur::orderBy('created_at', $order)
->paginate($pagination);
}
}
And in the controller create the array to pass as parameter:
$filters = [
'pagination' => 5,
'order' => 'asc',
];
or
$filters = [
'pagination' => 10,
'order' => 'desc',
];
Or you can get the values from the request (be sure to leave a default value in case the request input is null)
$filters = [
'pagination' => $request->input('pagination')?: 5,
'order' => $request->input('order')?: 'asc',
];
and then pass the parameter to the repo:
$auteurs = $this->auteurs->index($filters);
Hope it helps ;-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.