What you can do to reorder your blog posts in Laravel in chronological order?

Tip of the week series

Created on: June 05, 2018

Updated on: June 14, 2018

Written by Sehinde Raji

Tip of the week

What you can do to reorder your blog posts in Laravel in chronological order?

As you well know a blog is a diary that lists your articles in a chronological order.

In our web development services post we will be examining how you can create queries using Laravel's Eloquent to ensure that you get the right query for the blog that you are developing.

Laravel uses Eloquent and if you don’t already know eloquent is an Object Relational Mapper. This is so that you can work with the database objects and their subsequent relationships.

We use ORM in ormrepo to mean Object Relational Mapper and repo meaning repository.

What is a Scope?

A scope is a list of conditions that are applied to queries. Scopes are created on the model only.

In our case we have created a scope called latest and this sits on top of our web development services blog model.

Take a look at a few of our scopes listed below:


class Blog extends Model
{

    use  Sluggable, SluggableScopeHelpers, Searchable, Notifiable;

    // Add the fillable fields so that they are mass-assignable on this model.
    protected $fillable = ['title','series', 'feat_image', 'body', 'slug', 'user_id', 'published_at', 'tag' ];

/**
     * Find the published articles in a query scope.
     *
     * @param $query
     */
    public function scopePublished($query)
    {
        $query->where('published_at', '<=', Carbon::now()->toDateTimeString());
    }

     /**
     * Returns the latest published blog post.
     *
     * @param $query
     */
    public function scopeLatest($query)
    {
        return $query->where('published_at', '<=', Carbon::now());
    }

 }

As you can see our scopes use carbon which is a special format that inherits the time from the php DATETIME field.

Our latest scope reorders our blog posts in a chronological order from now.

How do we apply our scope?

The next stage is to apply this scope to the results of our blog listings page on our blogs controller.

Have a look at the snippet below to see this in action

 class BlogsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws MethodNotFoundException
     */

    public function index(Request $request)
    {

        {

                $blogs = blog::latest('published_at')->get()->all();

                $title = 'Blog Listings';

            }

        } catch (\Exception $e) {

            throw new MethodNotFoundException($e->getMessage());
        }

        return view('blogs.index', compact('blogs', 'title'));
    }

The scope is applied at the controller end this is because the scope is situation on the model itself which in this case refers to the web development services blog model.

What happens if you wanted to have all the blogs on that model ?

Well you would use the command:

   $blog = Blog::all();  

This pulls all of the blog posts from the model.

In today's post we learn't how to use query scopes with your models and how to apply them to your controller.

Let me know in the comments about your experiences with query scopes.

Stay tuned for further tips and tricks from www.ormrepo.co.uk/blogs.

The link also provides information about the web development services we offer.