laravel5.3开发知乎-第7章-问题列表+删除问题 laravel5.3开发知乎-第7章-问题列表+删除问题

2023-07-12

一、问题列表

app/Question.php 新增方法

public function user()
{
   return $this->belongsTo(User::class);
}

public function scopePublished($query)
{
   return $query->where('is_hidden','F');
}

app/Repositories/QuestionRepository.php 新增方法

public function getQuestionsFeed()
{
   return Question::published()->latest('updated_at')->with('user')->get();
}

修改 app/Providers/AppServiceProvider.php 的方法

public function register()
{
   if(version_compare(PHP_VERSION, '7.2.0', '>=')) {
       error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
   }
}

修改 app/Http/Controllers/QuestionsController.php

public function index()
{
   $questions = $this->questionRepository->getQuestionsFeed();
   return view('questions.index', compact('questions'));
}

修改 routes/web.php

Route::get('/', 'QuestionsController@index');

修改 app/Http/Controllers/Auth/LoginController.php

protected $redirectTo = '/';

修改 app/Http/Middlerware/RedirectIfAuthenticated.php

public function handle($request, Closure $next, $guard = null)
{
   if (Auth::guard($guard)->check()) {
       return redirect('/');
   }

   return $next($request);
}

新增 resources/views/questions/index.blade.php

https://file.lulublog.cn/images/3/2023/07/a4YU3U0ha1B4yroR0fvrBAaa0OO842.jpg

访问:http://127.0.0.1:8000/

二、删除问题

修改 app/Http/Controllers/QuestionsController.php

public function destroy($id)
{
   $question = $this->questionRepository->byId($id);
   if(Auth::user()->owns($question)){
       $question->delete();
       return redirect('/');
   }
   abort(403,'Forbidden');
}

修改 resources/views/questions/show.blade.php

https://file.lulublog.cn/images/3/2023/07/kjRGZs00gjiPPisJKtWx2GGGNHtTnk.jpg

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

阅读 270