Build an online forum with Laravel — Create routes, views, controllers. Generate auth. Write test (Part 2)
Part 1 — Initial setup and database seeding is available here.
tl;dr — Source code: https://github.com/connor11528/laravel-forum
Corresponding Laracasts lesson: https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/2
Routing and Controller
First create the route for viewing threads. Routes are defined in routes/web.php.
Route::get(‘/threads’, ‘ThreadController@index’);
The ThreadController is in app/Http/Controllers/ThreadController.php.
In that file return the latest threads:
class ThreadController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$threads = Thread::latest()->get();
return view('threads.index', compact('threads'));
}
‘Latest’ is a method that adds an order by to the timestamp. The full list of available methods is here.
Authentication
Next we’re going to add authentication to the application. This will also generate layout view files in the resources directory.
$ php artisan make:auth
Authentication scaffolding generated successfully.