Simple blog application in laravel 5 Part-2: Routes and Models

All parts of this series:

Simple blog application in laravel 5 - Introduction

Simple blog application in laravel 5 (part-1): Setup database

Simple blog application in laravel 5 (part-2): Routes and Models

Simple blog application in laravel 5 (part-3): Controllers

Simple blog application in laravel 5 (part-4): Build Front end

Simple blog application in laravel 5 (part-5): Add tinyMCE and User profile

Now we will make routes for our application. In routing we map urls with controllers. It is done using Route class. Route class provides get(), post(), delete(), put(), all() and match() functions for different types of requests from users. Here we are using only get() and post() functions for GET and POST type requests only. For more details about routes read Basic Routing in Laravel 5 and Advance Routing in Laravel 5. Change app/Http/routes.php with this code.

  1. <?php
  2. /*
  3. |--------------------------------------------------------------------------
  4. | Application Routes
  5. |--------------------------------------------------------------------------
  6. |
  7. | Here is where you can register all of the routes for an application.
  8. | It's a breeze. Simply tell Laravel the URIs it should respond to
  9. | and give it the controller to call when that URI is requested.
  10. |
  11. */
  12. Route::get('/','PostController@index');
  13. Route::get('/home',['as' => 'home', 'uses' => 'PostController@index']);
  14. //authentication
  15. Route::controllers([
  16. 'auth' => 'Auth\AuthController',
  17. 'password' => 'Auth\PasswordController',
  18. ]);
  19. // check for logged in user
  20. Route::group(['middleware' => ['auth']], function()
  21. {
  22. // show new post form
  23. Route::get('new-post','PostController@create');
  24. // save new post
  25. Route::post('new-post','PostController@store');
  26. // edit post form
  27. Route::get('edit/{slug}','PostController@edit');
  28. // update post
  29. Route::post('update','PostController@update');
  30. // delete post
  31. Route::get('delete/{id}','PostController@destroy');
  32. // display user's all posts
  33. Route::get('my-all-posts','UserController@user_posts_all');
  34. // display user's drafts
  35. Route::get('my-drafts','UserController@user_posts_draft');
  36. // add comment
  37. Route::post('comment/add','CommentController@store');
  38. // delete comment
  39. Route::post('comment/delete/{id}','CommentController@distroy');
  40. });
  41. //users profile
  42. Route::get('user/{id}','UserController@profile')->where('id', '[0-9]+');
  43. // display list of posts
  44. Route::get('user/{id}/posts','UserController@user_posts')->where('id', '[0-9]+');
  45. // display single post
  46. Route::get('/{slug}',['as' => 'post', 'uses' => 'PostController@show'])->where('slug', '[A-Za-z0-9-_]+');
  • A get() or post() function takes two arguments. First is the url which are requested in browsers. Second is the function or function name (pointed towards a function defined in controller class).
  • Here we are using controllers. Controllers are defined in folder app/Http/Controllers. We will make these controllers in next part. For more detail on controllers read Basic controllers in laravel 5 and advance controllers in laravel 5.
  • PostController@index means index() function of PostController class. We will make PostController class in next part.
  • For authentication (in line 19), we are using built-in authentication system of laravel. controller() function maps urls with directly function name like auth/login to login() function of AuthController class (defined in app/Http/Controllers/AuthController.php). For more on authentication system read Authentication in laravel 5.
  • In line 25, we are using auth middleware for restricting urls for only logged in users. Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For more detail read Middlewares in Laravel 5.

Create Models:

1) Posts Model:

Now create models for our tables so that we can use eloquent ORM. Models interact with database in a convenience manner. For read in details about eloquent ORM visit Eloquent ORM in Laravel 5. Create two files in app folder with names Posts.php and Comments.php. In Posts.php write this code:

  1. <?php namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. // instance of Posts class will refer to posts table in database
  4. class Posts extends Model {
  5. //restricts columns from modifying
  6. protected $guarded = [];
  7. // posts has many comments
  8. // returns all comments on that post
  9. public function comments()
  10. {
  11. return $this->hasMany('App\Comments','on_post');
  12. }
  13. // returns the instance of the user who is author of that post
  14. public function author()
  15. {
  16. return $this->belongsTo('App\User','author_id');
  17. }
  18. }

Posts class is associated with post table in database. $guarded variable is used to prevent inserting/ updating some columns of the table. We want to use all columns so $guarded array is empty. comments() function is associating comments with posts via one-many relation. author() function is returning the author of the post. This association is many to one relation.

2) Comments Model:

Similarly make model for comments table.

  1. <?php namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class Comments extends Model {
  4. //comments table in database
  5. protected $guarded = [];
  6. // user who has commented
  7. public function author()
  8. {
  9. return $this->belongsTo('App\User','from_user');
  10. }
  11. // returns post of any comment
  12. public function post()
  13. {
  14. return $this->belongsTo('App\Posts','on_post');
  15. }
  16. }

3) User Model

Modify the code of app/User.php and change it to:

  1. <?php namespace App;
  2. use Illuminate\Auth\Authenticatable;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Auth\Passwords\CanResetPassword;
  5. use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
  6. use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
  7. class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
  8. use Authenticatable, CanResetPassword;
  9. /**
  10. * The database table used by the model.
  11. *
  12. * @var string
  13. */
  14. protected $table = 'users';
  15. /**
  16. * The attributes that are mass assignable.
  17. *
  18. * @var array
  19. */
  20. protected $fillable = ['name', 'email', 'password'];
  21. /**
  22. * The attributes excluded from the model's JSON form.
  23. *
  24. * @var array
  25. */
  26. protected $hidden = ['password', 'remember_token'];
  27. // user has many posts
  28. public function posts()
  29. {
  30. return $this->hasMany('App\Posts','author_id');
  31. }
  32. // user has many comments
  33. public function comments()
  34. {
  35. return $this->hasMany('App\Comments','from_user');
  36. }
  37. public function can_post()
  38. {
  39. $role = $this->role;
  40. if($role == 'author' || $role == 'admin')
  41. {
  42. return true;
  43. }
  44. return false;
  45. }
  46. public function is_admin()
  47. {
  48. $role = $this->role;
  49. if($role == 'admin')
  50. {
  51. return true;
  52. }
  53. return false;
  54. }
  55. }

Here we have added four more function to the User class. posts() and comments() functions are associating user with posts and comments. can_post() is checking if user can post article or not. is_admin() function is checking if role is admin or not.



About Harish Kumar

Harish is an interested person in the field of web development and blogging. He works for the need of young web developers in learning various languages, latest technologies and other essential tips and tricks. If you need some help or you have some suggestion then you email him at harish@findalltogether.com without any hesitation. You can also suggest/demand for articles of your own choice.

Related Articles

Laravel is a MVC framework. Models are the real world entities in data form. Views are the response content to the vi...
Laravel framework architecture
Routes map urls with the controllers. In this section we will read about how route maps urls with controllers and how...
Basics routing and controllers in laravel 5
Views are the HTML content served by the server. These are served by returning from controllers. Views are .php or .b...
View in Laravel 5

Login or Sign up to leave comment.