Laravel 5.8 做个知乎 10 —— 添加回答

1 创建回复表

1.1 创建表

php artisan make:model Answer -m

databasemigrations2021_07_07_131436_create_answers_table.php

    public function up()
    {
        Schema::create('answers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->index()->unsigned();
            $table->integer('question_id')->index()->unsigned();
            $table->text('body');
            $table->integer('votes_count')->default(0);
            $table->integer('comments_count')->default(0);
            $table->string('is_hidden',8)->default('F');
            $table->string('close_comment',8) ->default('F');
            $table->timestamps();
        });
    }
View Code
php artisan migrate

1.2 创建关系

1.2.1 appAnswer.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Answer extends Model
{
    //
    protected $fillable=['user_id','question_id','body'];
    
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
    
}
View Code

1.2.2  appQuestion.php

public function answers()
{
      return $this->hasMany(Answer::class);
}

1.2.3  appTopic.php

    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
View Code

1.3 路由

outesweb.php

Route::post('questions/{question}/answer','AnswerController@store');

2 代码

2.1 控制器

php artisan make:controller AnswerController

appHttpControllersAnswerController.php

<?php

namespace AppHttpControllers;

use AppHttpRequestsStoreAnswerRequest;

use AppRepositoriesAnswerRepository;
use IlluminateSupportFacadesAuth;

class AnswerController extends Controller
{
    protected $answer;
    
    public function __construct(AnswerRepository $answer)
    {
        $this->middleware('auth');
        $this->answer = $answer;
    }
    public function store(StoreAnswerRequest $request,$question)
    {
        // dd($request->all());
        $answer = $this->answer->create([
            'question_id' =>$question,
            'user_id'   =>Auth::id(),
            'body'      =>$request->get('body')
        ]);
        $answer->question()->increment('answers_count');
        return back();
    }
}
View Code

appHttpControllersQuestionsController.php

查找回答列表

    public function show($id)
    {
        //$question = Question::where('id',$id)->with('topics')->first();
        $question =  $this->questionRepository->byIdWithTopicsAndAnswers($id);
        if(!$question){
            abort('404','你可能来到了没有知识的荒漠');
        }
        return view('questions.show',compact('question'));
    }

2.2 数据验证

php artisan make:request StoreAnswerRequest

appHttpRequestsStoreAnswerRequest.php

<?php

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;

class StoreAnswerRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
            'body'=>"required|min:20"
        ];
    }
    
    public function messages()
    {
        return [
          'body.required'=>'回答不得为空' ,
          'body.min'=>'回答不得少于20个字符'
        ];
    }
}
View Code

2.3 仓库层

2.3.1 appRepositoriesAnswerRepository.php

<?php
namespace AppRepositories;
use AppAnswer;

class  AnswerRepository
{
    public function create(array $attributes)
    {
        return Answer::create($attributes);
    }
}

2.3.2 appRepositoriesQuestionRepository.php

添加answers的绑定

 public function byIdWithTopicsAndAnswers($id)
    {
        $question = Question::where('id',$id)->with('topics','answers')->first();
        return $question;
    }

3 视图

esourcesviewsquestionsshow.blade.php

添加回答列表

@if(Auth::check())

                       <form action="/questions/{{$question->id}}/answer" method="post">
                           {!! csrf_field() !!}
                           <div class="form-group">

                               <label for="container"><h5>回答 </h5> </label>
                               <script id="container" name="body" type="text/plain" style = "height: 120px;">{!! old('body') !!}</script>

                               @if ($errors->any())
                               <div class="alert alert-danger">
                               <ul>
                                   @foreach ($errors->all() as $error)
                               <li>{{ $error }}</li>
                                   @endforeach
                               </ul>
                               </div>
                               @endif
                               <button class="btn btn-success pull-right" type="submit">提交</button>
                           </div>
                        </form>
                        @else
                        <?php
                         session(['redirectTo' => "/questions/$question->id"]);
                        ?>
                        <a href="{{url('login')}}?redirectTo=/questions/{{$question->id}}"  class="btn btn-success btn-block">登录提交答案</a>
                        @endif
View Code
原文地址:https://www.cnblogs.com/polax/p/14981341.html