Laravel Eloquent: API Resources

Introduction
When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application’s users. Laravel’s resource classes allow you to expressively and easily transform your models and model collections into JSON.

Generating Resources
To generate a resource class, you may use the make:resource Artisan command. By default, resources will be placed in the app/Http/Resources directory of your application. Resources extend the Illuminate\Http\Resources\Json\JsonResource class:

php artisan make:resource User

php artisan make:resource Users –collection
php artisan make:resource UserCollection

Concept Overview
Tip!! This is a high-level overview of resources and resource collections. You are highly encouraged to read the other sections of this documentation to gain a deeper understanding of the customization and power offered to you by resources.

Before diving into all of the options available to you when writing resources, let’s first take a high-level look at how resources are used within Laravel. A resource class represents a single model that needs to be transformed into a JSON structure. For example, here is a simple User resource class:

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when sending the response. Notice that we can access model properties directly from the $this variable. This is because a resource class will automatically proxy property and method access down to the underlying model for convenient access. Once the resource is defined, it may be returned from a route or controller:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

Resource Collections
If you are returning a collection of resources or a paginated response, you may use the collection method when creating the resource instance in your route or controller:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all());
});

Of course, this does not allow any addition of meta data that may need to be returned with the collection. If you would like to customize the resource collection response, you may create a dedicated resource to represent the collection:

Once the resource collection class has been generated, you may easily define any meta data that should be included with the response:

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}

After defining your resource collection, it may be returned from a route or controller:

use App\User;
use App\Http\Resources\UserCollection;
Route::get('/users', function () {
    return new UserCollection(User::all());
});

Customizing The Underlying Resource Class
Typically, the $this->collection property of a resource collection is automatically populated with the result of mapping each item of the collection to its singular resource class. The singular resource class is assumed to be the collection’s class name without the trailing Collection string.

For example, UserCollection will attempt to map the given user instances into the User resource. To customize this behavior, you may override the $collects property of your resource collection:

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
    /**
     * The resource that this resource collects.
     *
     * @var string
     */
    public $collects = 'App\Http\Resources\Member';
}

Writing Resources
Tip!! If you have not read the concept overview, you are highly encouraged to do so before proceeding with this documentation.
In essence, resources are simple. They only need to transform a given model into an array. So, each resource contains a toArray method which translates your model’s attributes into an API friendly array that can be returned to your users:

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

Relationships
If you would like to include related resources in your response, you may add them to the array returned by your toArray method. In this example, we will use the Post resource’s collection method to add the user’s blog posts to the resource response:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->posts),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

Resource Collections
While resources translate a single model into an array, resource collections translate a collection of models into an array. It is not absolutely necessary to define a resource collection class for each one of your model types since all resources provide a collection method to generate an “ad-hoc” resource collection on the fly:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all());
});
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}
{
    "data": [
        {
            "id": 1,
            "name": "Eladio Schroeder Sr.",
            "email": "therese28@example.com",
        },
        {
            "id": 2,
            "name": "Liliana Mayert",
            "email": "evandervort@example.com",
        }
    ]
}

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Http\Resources\Json\Resource;

class AppServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Resource::withoutWrapping();
}

/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}

Conditional Attributes
Sometimes you may wish to only include an attribute in a resource response if a given condition is met. For example, you may wish to only include a value if the current user is an “administrator”. Laravel provides a variety of helper methods to assist you in this situation. The when method may be used to conditionally add an attribute to a resource response:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'secret' => $this->when(Auth::user()->isAdmin(), 'secret-value'),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

Conditional Relationships
In addition to conditionally loading attributes, you may conditionally include relationships on your resource responses based on if the relationship has already been loaded on the model. This allows your controller to decide which relationships should be loaded on the model and your resource can easily include them only when they have actually been loaded.

Ultimately, this makes it easier to avoid “N+1” query problems within your resources. The whenLoaded method may be used to conditionally load a relationship. In order to avoid unnecessarily loading relationships, this method accepts the name of the relationship instead of the relationship itself:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'posts' => PostResource::collection($this->whenLoaded('posts')),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}

Eloquent: Mutators

Introduction
Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.

Accessors & Mutators

Defining An Accessor
To define an accessor, create a getFooAttribute method on your model where Foo is the “studly” cased name of the column you wish to access. In this example, we’ll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* Get the user’s first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may access the first_name attribute on a model instance:

$user = App\User::find(1);

$firstName = $user->first_name;
Of course, you may also use accessors to return new, computed values from existing attributes:

/**
* Get the user’s full name.
*
* @return string
*/
public function getFullNameAttribute()
{
return “{$this->first_name} {$this->last_name}”;
}
Defining A Mutator
To define a mutator, define a setFooAttribute method on your model where Foo is the “studly” cased name of the column you wish to access. So, again, let’s define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* Set the user’s first name.
*
* @param string $value
* @return void
*/
public function setFirstNameAttribute($value)
{
$this->attributes[‘first_name’] = strtolower($value);
}
}
The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model’s internal $attributes property. So, for example, if we attempt to set the first_name attribute to Sally:

$user = App\User::find(1);

$user->first_name = ‘Sally’;
In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its resulting value in the internal $attributes array.

Date Mutators
By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class to provide an assortment of helpful methods. You may customize which dates are automatically mutated, and even completely disable this mutation, by overriding the $dates property of your model:

namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
‘created_at’,
‘updated_at’,
‘deleted_at’
];
}
When a column is considered a date, you may set its value to a UNIX timestamp, date string (Y-m-d), date-time string, and of course a DateTime / Carbon instance, and the date’s value will automatically be correctly stored in your database:

$user = App\User::find(1);

$user->deleted_at = now();

$user->save();
As noted above, when retrieving attributes that are listed in your $dates property, they will automatically be cast to Carbon instances, allowing you to use any of Carbon’s methods on your attributes:

$user = App\User::find(1);

return $user->deleted_at->getTimestamp();
Date Formats
By default, timestamps are formatted as ‘Y-m-d H:i:s’. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
/**
* The storage format of the model’s date columns.
*
* @var string
*/
protected $dateFormat = ‘U’;
}
Attribute Casting
The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, and timestamp. When casting to decimal, you should define the number of digits, eg. decimal:2

For example, let’s cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a boolean value:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
‘is_admin’ => ‘boolean’,
];
}
Now the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

$user = App\User::find(1);

if ($user->is_admin) {
//
}
Array & JSON Casting
The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

‘array’,
];
}
Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

$user = App\User::find(1);

$options = $user->options;

$options[‘key’] = ‘value’;

$user->options = $options;

$user->save();
Date Casting
When using the date or datetime cast type, you may specify the date’s format. This format will be used when the model is serialized to an array or JSON:

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
‘created_at’ => ‘datetime:Y-m-d’,
];

collections

Introduction
All multi-result sets returned by Eloquent are instances of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends the Laravel base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models.

Of course, all collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

$users = App\User::where('active', 1)->get();

foreach ($users as $user) {
    echo $user->name;
}

However, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, let’s remove all inactive models and gather the first name for each remaining user:

$users = App\User::all();

$names = $users->reject(function ($user) {
    return $user->active === false;
})
->map(function ($user) {
    return $user->name;
});

Available Methods
The Base Collection
All Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class:
allaverageavgchunkcollapsecombineconcatcontainscontainsStrictcountcrossJoindddiffdiffKeysdumpeacheachSpreadeveryexceptfilterfirstflatMapflattenflipforgetforPagegetgroupByhasimplodeintersectisEmptyisNotEmptykeyBykeyslastmapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergeminmodenthonlypadpartitionpipepluckpopprependpullpushputrandomreducerejectreversesearchshiftshuffleslicesortsortBysortByDescsplicesplitsumtaketaptoArraytoJsontransformunionuniqueuniqueStrictunlessvalueswhenwherewhereStrictwhereInwhereInStrictwhereNotInwhereNotInStrictzip

Custom Collections
If you need to use a custom Collection object with your own extension methods, you may override the newCollection method on your model:

namespace App;
use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    /**
     * Create a new Eloquent Collection instance.
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new CustomCollection($models);
    }
}

Once you have defined a newCollection method, you will receive an instance of your custom collection anytime Eloquent returns a Collection instance of that model. If you would like to use a custom collection for every model in your application, you should override the newCollection method on a base model class that is extended by all of your models.

laravel relationships

Introduction
Database tables are often related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy, and supports several different types of relationships:

One To One
One To Many
Many To Many
Has Many Through
Polymorphic Relations
Many To Many Polymorphic Relations

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional constraints on this posts relationship:

$user->posts()->where(‘active’, 1)->get();
But, before diving too deep into using relationships, let’s learn how to define each type.

One To One
A one-to-one relationship is a very basic relation. For example, a User model might be associated with one Phone. To define this relationship, we place a phone method on the User model. The phone method should call the hasOne method and return its result:

namespace App;

use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent’s dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:

$phone = User::find(1)->phone;
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

return $this->hasOne(‘App\Phone’, ‘foreign_key’);
Additionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the user’s id column in the user_id column of the Phone record. If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key:

return $this->hasOne(‘App\Phone’, ‘foreign_key’, ‘local_key’);

Defining The Inverse Of The Relationship
So, we can access the Phone model from our User. Now, let’s define a relationship on the Phone model that will let us access the User that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

In the example above, Eloquent will try to match the user_id from the Phone model to an id on the User model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key');
}

If your parent model does not use id as its primary key, or you wish to join the child model to a different column, you may pass a third argument to the belongsTo method specifying your parent table’s custom key:

public function user()
{
    return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}

One To Many
A “one-to-many” relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the “snake case” name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.

Once the relationship has been defined, we can access the collection of comments by accessing the comments property. Remember, since Eloquent provides “dynamic properties”, we can access relationship methods as if they were defined as properties on the model:

$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
    //
}

Of course, since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query:

$comment = App\Post::find(1)->comments()->where('title', 'foo')->first();

One To Many (Inverse)
Now that we can access all of a post’s comments, let’s define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship function on the child model which calls the belongsTo method:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

In the example above, Eloquent will try to match the post_id from the Comment model to an id on the Post model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column. However, if the foreign key on the Comment model is not post_id, you may pass a custom key name as the second argument to the belongsTo method:

public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key');
}
public function post()
{
    return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}

Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of “Admin”. To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. For example, let’s define the roles method on our User model:

Defining The Inverse Of The Relationship
To define the inverse of a many-to-many relationship, you place another call to belongsToMany on your related model. To continue our user roles example, let’s define the users method on the Role model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

Retrieving Intermediate Table Columns
As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let’s assume our User object has many Role objects that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:

$user = App\User::find(1);
foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}

Customizing The pivot Attribute Name
As noted earlier, attributes from the intermediate table may be accessed on models using the pivot attribute. However, you are free to customize the name of this attribute to better reflect its purpose within your application.

For example, if your application contains users that may subscribe to podcasts, you probably have a many-to-many relationship between users and podcasts. If this is the case, you may wish to rename your intermediate table accessor to subscription instead of pivot. This can be done using the as method when defining the relationship:

Filtering Relationships Via Intermediate Table Columns
You can also filter the results returned by belongsToMany using the wherePivot and wherePivotIn methods when defining the relationship:
return $this->belongsToMany(‘App\Role’)->wherePivot(‘approved’, 1);

return $this->belongsToMany(‘App\Role’)->wherePivotIn(‘priority’, [1, 2]);

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User')->using('App\UserRole');
    }
}

The first argument passed to the hasManyThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.

Typical Eloquent foreign key conventions will be used when performing the relationship’s queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the hasManyThrough method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model:

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::morphMap([
    'posts' => 'App\Post',
    'videos' => 'App\Video',
]);
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
}
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get all of the posts for the user.
     */
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}
$user = App\User::find(1);

foreach ($user->posts as $post) {
    //
}
$posts = App\Post::has('comments')->get();
$posts = App\Post::has('comments', '>=', 3)->get();
$posts = App\Post::has('comments.votes')->get();
$posts = App\Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

Querying Relationship Absence
When accessing the records for a model, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don’t have any comments. To do so, you may pass the name of the relationship to the doesntHave and orDoesntHave methods:
Counting Related Models
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. For example:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}
$posts = App\Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo('App\Author');
    }
}

Constraining Eager Loads
Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here’s an example:

namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
    /**
     * All of the relationships to be touched.
     *
     * @var array
     */
    protected $touches = ['post'];

    /**
     * Get the post that the comment belongs to.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

laravel Eloquent

Eloquent ORMはLaravelに含まれており、美しくシンプルなアクティブレコードによるデーター操作の実装です。 それぞれのデータベーステーブルは関連する「モデル」と結びついている

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Before getting started, be sure to configure a database connection in config/database.php. For more information on configuring your database, check out the documentation.

Defining Models
To get started, let’s create an Eloquent model. Models typically live in the app directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file. All Eloquent models extend Illuminate\Database\Eloquent\Model class.

The easiest way to create a model instance is using the make:model Artisan command:

php artisan make:model Flight
php artisan make:model Flight --migration
php artisan make:model Flight -m

Eloquent Model Conventions
Now, let’s look at an example Flight model, which we will use to retrieve and store information from our flights database table:

Table Names
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the “snake case”, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table. You may specify a custom table by defining a table property on your model:

Primary Keys
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.

Timestamps
By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false:

Retrieving Models
Once you have created a model and its associated database table, you are ready to start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:

$flights = App\Flight::all();

foreach ($flights as $flight) {
    echo $flight->name;
}

Retrieving Single Models / Aggregates
Of course, in addition to retrieving all of the records for a given table, you may also retrieve single records using find or first. Instead of returning a collection of models, these methods return a single model instance:

Inserting & Updating Models
Inserts
To create a new record in the database, create a new model instance, set attributes on the model, then call the save method:

namespace App\Http\Controllers;

use App\Flight;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FlightController extends Controller
{
    /**
     * Create a new flight instance.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        // Validate the request...

        $flight = new Flight;

        $flight->name = $request->name;

        $flight->save();
    }
}

In this example, we assign the name parameter from the incoming HTTP request to the name attribute of the App\Flight model instance. When we call the save method, a record will be inserted into the database. The created_at and updated_at timestamps will automatically be set when the save method is called, so there is no need to set them manually.

Updates
The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

Interacting With Redis

Interacting With Redis
You may interact with Redis by calling various methods on the Redis facade. The Redis facade supports dynamic methods, meaning you may call any Redis command on the facade and the command will be passed directly to Redis. In this example, we will call the Redis GET command by calling the get method on the Redis facade

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        $user = Redis::get('user:profile:'.$id);
        return view('user.profile', ['user' => $user]);
    }
}

Of course, as mentioned above, you may call any of the Redis commands on the Redis facade. Laravel uses magic methods to pass the commands to the Redis server, so pass the arguments the Redis command expects:

Wildcard Subscriptions
Using the psubscribe method, you may subscribe to a wildcard channel, which may be useful for catching all messages on all channels. The $channel name will be passed as the second argument to the provided callback Closure:

Redis::psubscribe(['*'], function ($message, $channel) {
    echo $message;
});

Redis::psubscribe(['users.*'], function ($message, $channel) {
    echo $message;
});

Laravel Redis

Introduction
Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets.
Before using Redis with Laravel, you will need to install the predis/predis package via Composer:

composer require predis/predis

Alternatively, you may install the PhpRedis PHP extension via PECL. The extension is more complex to install but may yield better performance for applications that make heavy use of Redis.

Configuration
The Redis configuration for your application is located in the config/database.php configuration file. Within this file, you will see a redis array containing the Redis servers utilized by your application:

'redis' => [

    'client' => 'predis',

    'default' => [
        'host' => env('REDIS_HOST', 'localhost'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],

Laravel Database: Seeding

Introduction
Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

Writing Seeders
To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeds directory:

php artisan make:seeder UsersTableSeeder

A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

Using Model Factories
Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the model factory documentation to learn how to define your factories. Once you have defined your factories, you may use the factory helper function to insert records into your database.

For example, let’s create 50 users and attach a relationship to each user:

public function run()
{
    factory(App\User::class, 50)->create()->each(function ($u) {
        $u->posts()->save(factory(App\Post::class)->make());
    });
}

Calling Additional Seeders
Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Pass the name of the seeder class you wish to run:

public function run()
{
    $this->call([
        UsersTableSeeder::class,
        PostsTableSeeder::class,
        CommentsTableSeeder::class,
    ]);
}

Running Seeders
Once you have written your seeder, you may need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload

Now you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the –class option to specify a specific seeder class to run individually:

php artisan db:seed

php artisan db:seed –class=UsersTableSeeder
You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database:

php artisan migrate:refresh –seed

Database migration: laravel

Introduction
Migrations are like version control for your database, allowing your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.

The Laravel Schema facade provides database agnostic support for creating and manipulating tables across all of Laravel’s supported database systems.

Generating Migrations
To create a migration, use the make:migration Artisan command:

php artisan make:migration create_users_table

The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

The –table and –create options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options pre-fill the generated migration stub file with the specified table:

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users

If you would like to specify a custom output path for the generated migration, you may use the –path option when executing the make:migration command. The given path should be relative to your application’s base path.

Migration Structure
A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.

Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation. For example, this migration example creates a flights table:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

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

Running Migrations
To run all of your outstanding migrations, execute the migrate Artisan command:
php artisan migrate

Forcing Migrations To Run In Production
Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the –force flag:
php artisan migrate –force

To rollback the latest migration operation, you may use the rollback command. This command rolls back the last “batch” of migrations, which may include multiple migration files:

php artisan migrate:rollback
You may rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last five migrations:

php artisan migrate:rollback –step=5
The migrate:reset command will roll back all of your application’s migrations:

php artisan migrate:reset

Rollback & Migrate In Single Command
The migrate:refresh command will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database:

php artisan migrate:refresh

// Refresh the database and run all database seeds…
php artisan migrate:refresh –seed
You may rollback & re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will rollback & re-migrate the last five migrations:
php artisan migrate:refresh –step=5

Drop All Tables & Migrate
The migrate:fresh command will drop all tables from the database and then execute the migrate command:

php artisan migrate:fresh

php artisan migrate:fresh –seed

Creating Tables
To create a new database table, use the create method on the Schema facade. The create method accepts two arguments. The first is the name of the table, while the second is a Closure which receives a Blueprint object that may be used to define the new table:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
});

Database Connection & Table Options
If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:

Schema::connection(‘foo’)->create(‘users’, function (Blueprint $table) {
$table->increments(‘id’);
});

Command Description
$table->engine = ‘InnoDB’; Specify the table storage engine (MySQL).
$table->charset = ‘utf8’; Specify a default character set for the table (MySQL).
$table->collation = ‘utf8_unicode_ci’; Specify a default collation for the table (MySQL).
$table->temporary(); Create a temporary table (except SQL Server).

Creating Columns
The table method on the Schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments: the name of the table and a Closure that receives a Blueprint instance you may use to add columns to the table:
Schema::table(‘users’, function (Blueprint $table) {
$table->string(’email’);
});

Available Column Types
Of course, the schema builder contains a variety of column types that you may specify when building your tables:

Command Description
$table->bigIncrements(‘id’); Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger(‘votes’); BIGINT equivalent column.
$table->binary(‘data’); BLOB equivalent column.
$table->boolean(‘confirmed’); BOOLEAN equivalent column.
$table->char(‘name’, 100); CHAR equivalent column with an optional length.
$table->date(‘created_at’); DATE equivalent column.
$table->dateTime(‘created_at’); DATETIME equivalent column.
$table->dateTimeTz(‘created_at’); DATETIME (with timezone) equivalent column.
$table->decimal(‘amount’, 8, 2); DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->double(‘amount’, 8, 2); DOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
$table->enum(‘level’, [‘easy’, ‘hard’]); ENUM equivalent column.
$table->float(‘amount’, 8, 2); FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry(‘positions’); GEOMETRY equivalent column.
$table->geometryCollection(‘positions’); GEOMETRYCOLLECTION equivalent column.
$table->increments(‘id’); Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->integer(‘votes’); INTEGER equivalent column.
$table->ipAddress(‘visitor’); IP address equivalent column.
$table->json(‘options’); JSON equivalent column.
$table->jsonb(‘options’); JSONB equivalent column.
$table->lineString(‘positions’); LINESTRING equivalent column.
$table->longText(‘description’); LONGTEXT equivalent column.
$table->macAddress(‘device’); MAC address equivalent column.
$table->mediumIncrements(‘id’); Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
$table->mediumInteger(‘votes’); MEDIUMINT equivalent column.
$table->mediumText(‘description’); MEDIUMTEXT equivalent column.
$table->morphs(‘taggable’); Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
$table->multiLineString(‘positions’); MULTILINESTRING equivalent column.
$table->multiPoint(‘positions’); MULTIPOINT equivalent column.
$table->multiPolygon(‘positions’); MULTIPOLYGON equivalent column.
$table->nullableMorphs(‘taggable’); Adds nullable versions of morphs() columns.
$table->nullableTimestamps(); Alias of timestamps() method.
$table->point(‘position’); POINT equivalent column.
$table->polygon(‘positions’); POLYGON equivalent column.
$table->rememberToken(); Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->smallIncrements(‘id’); Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
$table->smallInteger(‘votes’); SMALLINT equivalent column.
$table->softDeletes(); Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
$table->softDeletesTz(); Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
$table->string(‘name’, 100); VARCHAR equivalent column with a optional length.
$table->text(‘description’); TEXT equivalent column.
$table->time(‘sunrise’); TIME equivalent column.
$table->timeTz(‘sunrise’); TIME (with timezone) equivalent column.
$table->timestamp(‘added_on’); TIMESTAMP equivalent column.
$table->timestampTz(‘added_on’); TIMESTAMP (with timezone) equivalent column.
$table->timestamps(); Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
$table->timestampsTz(); Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
$table->tinyIncrements(‘id’); Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger(‘votes’); TINYINT equivalent column.
$table->unsignedBigInteger(‘votes’); UNSIGNED BIGINT equivalent column.
$table->unsignedDecimal(‘amount’, 8, 2); UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->unsignedInteger(‘votes’); UNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger(‘votes’); UNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger(‘votes’); UNSIGNED SMALLINT equivalent column.
$table->unsignedTinyInteger(‘votes’); UNSIGNED TINYINT equivalent column.
$table->uuid(‘id’); UUID equivalent column.
$table->year(‘birth_year’); YEAR equivalent column.

Column Modifiers
In addition to the column types listed above, there are several column “modifiers” you may use while adding a column to a database table. For example, to make the column “nullable”, you may use the nullable method:

Modifier Description
->after(‘column’) Place the column “after” another column (MySQL)
->autoIncrement() Set INTEGER columns as auto-increment (primary key)
->charset(‘utf8’) Specify a character set for the column (MySQL)
->collation(‘utf8_unicode_ci’) Specify a collation for the column (MySQL/SQL Server)
->comment(‘my comment’) Add a comment to a column (MySQL)
->default($value) Specify a “default” value for the column
->first() Place the column “first” in the table (MySQL)
->nullable($value = true) Allows (by default) NULL values to be inserted into the column
->storedAs($expression) Create a stored generated column (MySQL)
->unsigned() Set INTEGER columns as UNSIGNED (MySQL)
->useCurrent() Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
->virtualAs($expression) Create a virtual generated column (MySQL)
->generatedAs($expression) Create an identity column with specified sequence options (PostgreSQL)
->always() Defines the precedence of sequence values over input for an identity column (PostgreSQL)

Updating Column Attributes
The change method allows you to modify some existing column types to a new type or modify the column’s attributes. For example, you may wish to increase the size of a string column. To see the change method in action, let’s increase the size of the name column from 25 to 50:

Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});

Laravel pagenation

In other frameworks, pagination can be very painful. Laravel’s paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database results out of the box. The HTML generated by the paginator is compatible with the Bootstrap CSS framework.

Basic Usage
Paginating Query Builder Results

There are several ways to paginate items. The simplest is by using the paginate method on the query builder or an Eloquent query. The paginate method automatically takes care of setting the proper limit and offset based on the current page being viewed by the user. By default, the current page is detected by the value of the page query string argument on the HTTP request. Of course, this value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator.

In this example, the only argument passed to the paginate method is the number of items you would like displayed “per page”. In this case, let’s specify that we would like to display 15 items per page:

amespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show all of the users for the application.
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::table('users')->paginate(15);

        return view('user.index', ['users' => $users]);
    }
}

“Simple Pagination”
If you only need to display simple “Next” and “Previous” links in your pagination view, you may use the simplePaginate method to perform a more efficient query. This is very useful for large datasets when you do not need to display a link for each page number when rendering your view:

$users = DB::table(‘users’)->simplePaginate(15);

Paginating Eloquent Results
You may also paginate Eloquent queries. In this example, we will paginate the User model with 15 items per page. As you can see, the syntax is nearly identical to paginating query builder results:

$users = App\User::paginate(15);

Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator instance, depending on your needs.

The Paginator class does not need to know the total number of items in the result set; however, because of this, the class does not have methods for retrieving the index of the last page. The LengthAwarePaginator accepts almost the same arguments as the Paginator; however, it does require a count of the total number of items in the result set.

In other words, the Paginator corresponds to the simplePaginate method on the query builder and Eloquent, while the LengthAwarePaginator corresponds to the paginate method.

When calling the paginate method, you will receive an instance of Illuminate\Pagination\LengthAwarePaginator. When calling the simplePaginate method, you will receive an instance of Illuminate\Pagination\Paginator. These objects provide several methods that describe the result set. In addition to these helpers methods, the paginator instances are iterators and may be looped as an array. So, once you have retrieved the results, you may display the results and render the page links using Blade:

<div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $users->links() }}
Route::get('users', function () {
    $users = App\User::paginate(15);

    $users->withPath('custom/url');

    //
});
{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "first_page_url": "http://laravel.app?page=1",
   "last_page_url": "http://laravel.app?page=4",
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "path": "http://laravel.app",
   "from": 1,
   "to": 15,
   "data":[
        {
            // Result Object
        },
        {
            // Result Object
        }
   ]
}

$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (Not available when using simplePaginate)
$results->nextPageUrl()
$results->onFirstPage()
$results->perPage()
$results->previousPageUrl()
$results->total() (Not available when using simplePaginate)
$results->url($page)