一、reponsitory
新建 app/Repositories/QuestionRepository.php
namespace App\Repositories;
use App\Question;
use App\Topic;
class QuestionRepository
{
public function byIdWithTopics($id)
{
return Question::where('id', $id)->with('topics')->first();
}
public function create(array $attributes)
{
return Question::create($attributes);
}
public function normalizeTopic(array $topics)
{
return collect($topics)->map(function ($topic){
if(is_numeric($topic)){
Topic::find($topic)->increment('questions_count');
return (int) $topic;
}
$newTopic = Topic::create(['name'=>$topic,'questions_count'=>1]);
return $newTopic->id;
})->toArray();
}
}
修改 app/Http/Controllers/QuestionsController.php
protected $questionRepository;
public function __construct(QuestionRepository $questionRepository)
{
$this->middleware('auth')->except(['index','show']);
$this->questionRepository = $questionRepository;
}
public function store(StoreQuestionRequest $request)
{
$topics = $this->questionRepository->normalizeTopic($request->get('topics'));
$data = [
'title' => $request->get('title'),
'content' => $request->get('content'),
'user_id' => Auth::id()
];
$question = $this->questionRepository->create($data);
$question->topics()->attach($topics);
return redirect()->route('questions.show',[$question->id]);
}
public function show($id)
{
$question = $this->questionRepository->byIdWithTopics($id);
return view('questions.show', compact('question'));
}
二、编辑问题
修改 app/Repositories/QuestionRepository.php
public function byId($id)
{
return Question::find($id);
}
修改 app/User.php
public function owns(Model $model)
{
return $this->id == $model->user_id;
}
修改 app/Http/Controllers/QuestionsController.php
public function edit($id)
{
$question = $this->questionRepository->byId($id);
if(Auth::user()->owns($question)){
return view('questions.edit', compact('question'));
}
return back();
}
public function update(StoreQuestionRequest $request, $id)
{
$question = $this->questionRepository->byId($id);
$topics = $this->questionRepository->normalizeTopic($request->get('topics'));
$question->update([
'title' => $request->get('title'),
'content' => $request->get('content'),
]);
$question->topics()->sync($topics);
return redirect()->route('questions.show',[$question->id]);
}
修改 resources/views/questions/show.blade.php
新建 resources/views/questions/edit.blade.php
注意:vendor.ueditor.assets 必须在 js 后面
@section('js')
@include('vendor.ueditor.assets')