Patrick Müller writing nonsense since 2019

Setting up models in Laravel

This post was written before the blog was somehow taken over by photography and never got released. So while I am sure there must be some reason for that, I am releasing it now since the topic seems interesting for people using Laravel:

At first glance creating a model on laravel is easy as typing "php artisan make:model User" and being done with it. Of course there is a little more to do and so here are few points that you might want to remember. Let's see a very basic example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Request extends Model
{

    use SoftDeletes;

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function items()
    {
        return $this->hasMany('App\Item');
    }

    /**
     * @param User $user
     */
    public function setUser(User $user)
    {
        $this->update(['user_id' =>  $user->id]);
    }
}

The first sind you will notice is that I am importing the SoftDeletes trait. I find this a good practise to do early on so that I can ensure that if the requirement of getting "deleted" data back comes up later this is no problem. Essentially it will use a datetime field called "deleted_at" to markt items as deleted and Eloquent will ensure that selects don't cover deleted items unless it's told to do otherwise.

Another handy thing is not to constantly handle foreignkeys in your controllers by simply adding a method to create the association in question by injecting not the key but the model itself into it.

Other goodies

At least for me it's quite a common thing to want to display what are essentially tables of one model or another that are sortable by a given column, in those cases column-sortable is a great package for laravel. Just import the Sortable trait, declare what columns should be available for sorting by and you are almost set:

// ...

    use Sortable;

    public $sortable = ['id', 'created_at'];

// ...

Now you can use a nice set of helpers to get sortable tables in your blade views.