Simple blog application in laravel 5 Part-3: Controllers

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 controllers for our application. Use following commands for generating controllers:

  1. php artisan make:controller UserController
  2. php artisan make:controller PostController
  3. php artisan make:controller CommentController

These commands will create three files in app/Http/Controllers folder. For more details about controllers read Basic Controllers in Laravel 5 and Advance Controllers in Laravel 5.

PostController:

We will send view files (html text) after operating requests. We will form these view files in next tutorial. Open app/Http/Controllers/PostController.php file.

Show all posts:

On the home page we want to show 5 posts with pagination for other posts. index() function of PostController class is handling root request (localhost:8000). So update index() function as:

  1. public function index()
  2. {
  3. //fetch 5 posts from database which are active and latest
  4. $posts = Posts::where('active',1)->orderBy('created_at','desc')->paginate(5);
  5. //page heading
  6. $title = 'Latest Posts';
  7. //return home.blade.php template from resources/views folder
  8. return view('home')->withPosts($posts)->withTitle($title);
  9. }

Create new post:

For creating a new post, we have to send a form to the user request. First we will check if requested user has permissions for posting or not (only authors and admin can post) then we will return form for creating post. Update create() function as:

  1. public function create(Request $request)
  2. {
  3. // if user can post i.e. user is admin or author
  4. if($request->user()->can_post())
  5. {
  6. return view('posts.create');
  7. }
  8. else
  9. {
  10. return redirect('/')->withErrors('You have not sufficient permissions for writing post');
  11. }
  12. }

Till now we have not created 'post.create' view. This view contains the html code of the form. We will create this view in next part of this series.

Storing posts:

When user will submit the form then we need to validate the form and then store it. For validation, we are using PostFormRequest. Create a file with name PostFormRequest.php in app/Http/Requests and write down this code:

  1. <?php namespace App\Http\Requests;
  2. use App\Http\Requests\Request;
  3. use App\User;
  4. use Auth;
  5. class PostFormRequest extends Request {
  6. /**
  7. * Determine if the user is authorized to make this request.
  8. *
  9. * @return bool
  10. */
  11. public function authorize()
  12. {
  13. if($this->user()->can_post())
  14. {
  15. return true;
  16. }
  17. return false;
  18. }
  19. /**
  20. * Get the validation rules that apply to the request.
  21. *
  22. * @return array
  23. */
  24. public function rules()
  25. {
  26. return [
  27. 'title' => 'required|unique:posts|max:255',
  28. 'title' => array('Regex:/^[A-Za-z0-9 ]+$/'),
  29. 'body' => 'required',
  30. ];
  31. }
  32. }

authorize() function checks if user has right to submitting this form. If user has right for posting then received data will be validate. The rules of the validation are defined by rules() function. Multiple rules on same data (like title) are separated by pipe (|).

We will use this validation in our PostController class. Update the store() function with this code.

  1. public function store(PostFormRequest $request)
  2. {
  3. $post = new Posts();
  4. $post->title = $request->get('title');
  5. $post->body = $request->get('body');
  6. $post->slug = str_slug($post->title);
  7. $post->author_id = $request->user()->id;
  8. if($request->has('save'))
  9. {
  10. $post->active = 0;
  11. $message = 'Post saved successfully';
  12. }
  13. else
  14. {
  15. $post->active = 1;
  16. $message = 'Post published successfully';
  17. }
  18. $post->save();
  19. return redirect('edit/'.$post->slug)->withMessage($message);
  20. }

Also don't forget to include PostFormRequest in PostController.php. Updata the top section of PostController.php:

  1. <?php namespace App\Http\Controllers;
  2. use App\Posts;
  3. use App\User;
  4. use Redirect;
  5. use App\Http\Controllers\Controller;
  6. use App\Http\Requests\PostFormRequest;
  7. use Illuminate\Http\Request;
  8. class PostController extends Controller {
  9. //other code/ functions below

Show full single posts along with comments:

  1. public function show($slug)
  2. {
  3. $post = Posts::where('slug',$slug)->first();
  4. if(!$post)
  5. {
  6. return redirect('/')->withErrors('requested page not found');
  7. }
  8. $comments = $post->comments;
  9. return view('posts.show')->withPost($post)->withComments($comments);
  10. }

This function is taking slug as argument and in line 3 post is fetched from database. If post exits then we are fetching comments. This relation between Post model and comments is defined in comments() function in Post model.

Single page of demo blogging website
Single Page of blogging post

Edit Post:

Now we will send form for editing a post:

  1. public function edit(Request $request,$slug)
  2. {
  3. $post = Posts::where('slug',$slug)->first();
  4. if($post && ($request->user()->id == $post->author_id || $request->user()->is_admin()))
  5. return view('posts.edit')->with('post',$post);
  6. return redirect('/')->withErrors('you have not sufficient permissions');
  7. }

In line 3 we are fetching the post from the database and in line 4 we are checking that user who is requesting is a valid user (admin or author of that post) or not.

Update post:

We will receive this edit form and will update database.

  1. public function update(Request $request)
  2. {
  3. //
  4. $post_id = $request->input('post_id');
  5. $post = Posts::find($post_id);
  6. if($post && ($post->author_id == $request->user()->id || $request->user()->is_admin()))
  7. {
  8. $title = $request->input('title');
  9. $slug = str_slug($title);
  10. $duplicate = Posts::where('slug',$slug)->first();
  11. if($duplicate)
  12. {
  13. if($duplicate->id != $post_id)
  14. {
  15. return redirect('edit/'.$post->slug)->withErrors('Title already exists.')->withInput();
  16. }
  17. else
  18. {
  19. $post->slug = $slug;
  20. }
  21. }
  22. $post->title = $title;
  23. $post->body = $request->input('body');
  24. if($request->has('save'))
  25. {
  26. $post->active = 0;
  27. $message = 'Post saved successfully';
  28. $landing = 'edit/'.$post->slug;
  29. }
  30. else {
  31. $post->active = 1;
  32. $message = 'Post updated successfully';
  33. $landing = $post->slug;
  34. }
  35. $post->save();
  36. return redirect($landing)->withMessage($message);
  37. }
  38. else
  39. {
  40. return redirect('/')->withErrors('you have not sufficient permissions');
  41. }
  42. }

Delete Post:

Final function of PostController is destroy(). It deletes the post. Only author and admin has right to delete the post.

  1. public function destroy(Request $request, $id)
  2. {
  3. //
  4. $post = Posts::find($id);
  5. if($post && ($post->author_id == $request->user()->id || $request->user()->is_admin()))
  6. {
  7. $post->delete();
  8. $data['message'] = 'Post deleted Successfully';
  9. }
  10. else
  11. {
  12. $data['errors'] = 'Invalid Operation. You have not sufficient permissions';
  13. }
  14. return redirect('/')->with($data);
  15. }

CommentController:

For simplicity purpose we are defining only one method for creating comments. For adding more features you can define more functions to CommentController just like we have added to PostController.

  1. <?php namespace App\Http\Controllers;
  2. use App\Posts;
  3. use App\Comments;
  4. use Redirect;
  5. use App\Http\Requests;
  6. use App\Http\Controllers\Controller;
  7. use Illuminate\Http\Request;
  8. class CommentController extends Controller {
  9. public function store(Request $request)
  10. {
  11. //on_post, from_user, body
  12. $input['from_user'] = $request->user()->id;
  13. $input['on_post'] = $request->input('on_post');
  14. $input['body'] = $request->input('body');
  15. $slug = $request->input('slug');
  16. Comments::create( $input );
  17. return redirect($slug)->with('message', 'Comment published');
  18. }
  19. }

At this time we are not adding any code to UserController. We will use this controller for displaying posts and drafts of indivisible author and also for creating profile for users. We will define this controller in 5th part of this tutorial series.



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.