这是我的类TagRepository:
<?php
namespace App\Repositories;
use App\Tag;
use Illuminate\Support\Str;``
use App\Repositories\TagRepository;
class TagRepository
{
protected $tag;
public function __construct(Tag $tag)
{
$this->tag = $tag;
}
public function store($post, $tags)
{
$tags = explode(',', $tags);
foreach ($tags as $tag) {
$tag = trim($tag);
$tag_url = Str::slug($tag);
$tag_ref = $this->tag->where('tag_url', $tag_url)->first();
if(is_null($tag_ref))
{
$tag_ref = new $this->tag([
'tag' => $tag,
'tag_url' => $tag_url
]);
$post->tags()->save($tag_ref);
} else {
$post->tags()->attach($tag_ref->id);
}
}
}
}
and this my controller
<?php
namespace App\Http\Controllers;
use App\Repositories\PostRepository;
use App\Http\Requests\PostRequest;
use App\Repositories\TagRepository;
class PostController extends Controller
{
protected $postRepository;
protected $nbrPerPage = 4;
public function __construct(PostRepository $postRepository)
{
$this->middleware('auth', ['except' => ['index', 'indexTag']]);
$this->middleware('admin', ['only' => 'destroy']);
$this->postRepository = $postRepository;
}
public function index()
{
$posts = $this->postRepository->getWithUserAndTagsPaginate($this->nbrPerPage);
$links = $posts->render();
return view('posts.liste', compact('posts', 'links'));
}
public function create()
{
return view('posts.add');
}
public function store(PostRequest $request, TagRepository $tagRepository)
{
$inputs = array_merge($request->all(), ['user_id' => $request->user()->id]);
$post = $this->postRepository->store($inputs);
if(isset($inputs['tags']))
{
$tagRepository->store($post, $inputs['tags']);
}
return redirect(route('post.index'));
}
public function destroy($id)
{
$this->postRepository->destroy($id);
return redirect()->back();
}
public function indexTag($tag)
{
$posts = $this->postRepository->getWithUserAndTagsForTagPaginate($tag, $this->nbrPerPage);
$links = $posts->render();
return view('posts.liste', compact('posts', 'links'))
->with('info', 'Résultats pour la recherche du mot-clé : ' . $tag);
}
}`
这是我的要求:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Repositories\TagRepository;
class PostRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'titre' => 'required|max:80',
'contenu' => 'required',
'tags' => ['Regex:/^[A-Za-z0-9-éèàù]{1,50}?(,[A-Za-z0-9-éèàù]{1,50})*$/']
];
}
}