We have to create two pages, index and posts, so we need :

  • two views : index view for list of posts and post view
  • controller to manipulate posts (e.g. building urls, getting social network data) and passing them to view 
  • model  to get all posts or get full details of specific texts
  • migrate to build our blog's table
  • panel to add, edit or update the blog

Schema and Migration

We need few fields for the blog :

  • id
  • title
  • image
  • author
  • content (content of post)
  • socialPoint (number of people who have shared this post in social networks)
  • created_at (creation date)
  • updated_at(date of last update)

 

To create the blog table, first we need to build the migration in laravel.

Go to path of your laravel project from the command line and run the following command :

php artisan migrate:make create_blog

Add the following lines to  app/database/migrations :

public function up()
	{
		Schema::create('blog', function($table)
                {
                    $table->increments('id');
                    $table->string('title',256);
                    $table->string('image',256);
                    $table->string('author',256);
                    $table->longText('content');
                    $table->bigInteger('socialPoint');
                    $table->timestamps();
                });

	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
            Schema::drop('blog');
	}

Then run the following command to build the tables :

php artisan migrate

Model, Controller, Routes

In blog model we need the function that fetches the last post, most recommended post, next and previous posts of one specific post and a function to make the blog url. So we create the Blog.php file in app/models directory and write the following code :

class Blog extends Eloquent {
    //put your code here
    protected  $table = 'blog';
    
    // return url of blog post 
    function getUrl(){
        return Config::get('app.url') .'/blog/post/'. $this->id . '/' . BlogController::seoUrl($this->title);
    }
    
    public static  function mostRecommended(){
        return  Blog::orderBy('socialPoint','desc')->where('public', 1)->take(1)->get()->first();
    }
    public function nextPost(){
        // get next post
        return Blog::where('id', '>', $this->id)->where('public', 1)->orderBy('id','asc')->take(1)->get()->first();
    }
    public  function previousPost(){
        // get previous  post 
        return Blog::where('id', '<', $this->id)->where('public', 1)->orderBy('id','desc')->take(1)->get()->first();
    }
    
    public static  function lastPosts(){
        return Blog::orderBy('created_at','desc')->where('public', 1)->get();
    }
}

The next step is making the blog controller. It should get the posts from model and pass them to view. It also has a function for generating social network links (useful for sharing the post) and a function for generating seo friendly url. We create the BlogController.php file in app/controllers directory and write the following lines of code :

class BlogController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 * GET /blog
	 *
	 * @return Response
	 */
	public function getIndex()
	{
            $mostRecommended = Blog::mostRecommended();
            $last            = Blog::lastPosts();
            return View::make('blog.index',array('title'=>"Wellcome ",'mostRecommended'=>$mostRecommended,'last'=>$last));
	}

    public static function seoUrl($string) {
        //Lower case everything
        $string = strtolower($string);
        //Make alphanumeric (removes all other characters)
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }
	/**
	 * Display the specified resource.
	 * GET /blog/{id}/title
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function getPost($id)
	{
            $post = Blog::find($id);
            if($post == NULL){
                App::abort(404);
            }
            return View::make('blog.post',array('title'=>$post['title'],'post'=>$post));
	}
        
    /**
     * Add the point to  
     * 
     * 
     */ 
    public function getShare($id,$social)
    {
        $url = '';
        $post = Blog::find($id);
        if($post == NULL){
            App::abort(404);
        }
        // add social point 
        $post->socialPoint ++;
        $post->save();
        switch ($social){
            case 'twitter' :
                $url  = 'https://twitter.com/home?status=';
                $url .= $post['title'] . ' ' . $post->getUrl();
            break;
            case 'facebook' :
                $url  = 'https://www.facebook.com/sharer/sharer.php?u=';
                $url .=  $post->getUrl();
            break;
            case 'googlePlus' :
                $url  = 'https://plus.google.com/share?url=';
                $url .= $post->getUrl();
            break;
            case 'linkedIn' :
                $url  = 'https://www.linkedin.com/shareArticle?mini=true&';
                $url .= 'url='.$post->getUrl().'&title='.$post['title'].'&summary=&source=';
            break;          
        }
        return Redirect::to($url);
    }



}

And finally we should set the route for the blog. So we open the routes.php file in app directory and add our route :

Route::controller('/blog', 'BlogController');

Views

We should create a folder inside the views folder named 'blog' and create the index.blade.php file for listing the last post and also we should create the post.blade.php file for showing contents of each post.

If you don't have your own template you can use the free blog template.

In index.blade.php, you should add the following lines to show most recommended posts :

MOST RECOMMENDED

{{$mostRecommended['title']}}
{{substr($mostRecommended['content'], 0, 150);}}...

{{$mostRecommended['author']}}

@foreach($last as $post)
 
{{$post['title']}}

{{substr(strip_tags($post['content']), 0, 150);}}...

{{$post['author']}}
        @endforeach

And in post.blade.php, you should add the following lines : 

{{$post['title']}}

{{$post['socialPoint']}} People did share it .

by {{$post['author']}} — Posted in Serverfire on {{$post['created_at']}}

{{$post['content']}}
If you've enjoyed this post, share it in social networks:

facebook twitter googlePlus linkedIn

@if($post->nextPost())
Next : {{$post->nextPost()['title']}}
 @endif

@if($post->previousPost())
Previus : {{$post->previousPost()['title']}}
@endif

Panel

Finally you need a CRUD (create, read, update, delete) for the blog. You should use the Serverfire Panel.This package provides an easily configurable admin panel for Laravel applications. You can easily install and use it.

After completing the installation, to build the blog CRUD, first add the blog entity to panel. In app/config/packages/serverfireteam/panel/config.php file, add the blog entity to crudItems array :

'crudItems' => array(
...
 "Blog" => "Blog" ,
...
)

Then you need to create the controller for this entity, so create a folder named panel in app/controllers then create the BlogController.php file and add the following lines of code :

<?php
namespace App\Controllers\panel;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
use Serverfireteam\Panel\CrudController;
use \Illuminate\Routing\Controllers;
/**
 * Description of Blog
 *
 * @author alireza
 */
class BlogController extends \Serverfireteam\Panel\CrudController {
    //put your code here
     public  function all($entity){
        
        parent::all($entity); 
        
        $this->filter = \DataFilter::source(new \Blog());
        $this->filter->add('id', 'ID', 'text');
        $this->filter->add('title', 'Title', 'text');
        $this->filter->submit('search');
        $this->filter->reset('reset');
        $this->filter->build();
                
        $this->grid = \DataGrid::source($this->filter);
        $this->grid->add('id','ID', true)->style("width:100px");
        $this->grid->add('title','title');
        $this->grid->add('socialPoint','social Point');
        $this->addStylesToGrid();           
                       
        return $this->returnView();
    }
           
    
    public function edit($entity){
        
        parent::edit($entity);
              
        $this->edit = \DataEdit::source(new \Blog());
        
        $this->edit->label('Edit Project');     
        $this->edit->add('title','post title', 'text')->rule('required|min:3');
        $this->edit->add('author','author', 'text')->rule('required|min:2');   
        $this->edit->add('content','content', 'textarea')->rule('required');
        $this->edit->add('image','image', 'image')->move('uploads/');
      
        return $this->returnEditView();
    }
}

Its done! Now you can go to yoursite/panel/blog/all url and add the posts.