Permalink
Browse files

added firstOrCreate and firstOrNew methods to Eloquent query builder.

  • Loading branch information...
taylorotwell committed Oct 2, 2013
1 parent 6f36d65 commit fce86bc9b53cb693284ea1dc557b3034375fd1ca
Showing with 52 additions and 1 deletion.
  1. +50 −0 src/Illuminate/Database/Eloquent/Model.php
  2. +2 −1 src/Illuminate/Foundation/changes.json
@@ -378,6 +378,56 @@ public static function create(array $attributes)
return $model;
}
/**
* Get the first record matching the attributes or create it.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public static function firstOrCreate(array $attributes)
{
if ( ! is_null($instance = static::firstByAttributes($attributes)))
{
return $instance;
}
return static::create($attributes);
}
/**
* Get the first record matching the attributes or instantiate it.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public static function firstOrNew(array $attributes)
{
if ( ! is_null($instance = static::firstByAttributes($attributes)))
{
return $instance;
}
return new static($attributes);
}
/**
* Get the first model for the given attributes.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model|null
*/
protected static function firstByAttributes($attributes)
{
$query = static::query();
foreach ($attributes as $key => $value)
{
$query->where($key, $value);
}
return $query->first() ?: null;
}
/**
* Begin querying the model.
*
@@ -44,6 +44,7 @@
{"message": "Implement JSONable and Arrayable interfaces on Paginator.", "backport": null},
{"message": "Foreign characters now supported in validation 'alpha' rules.", "backport": null},
{"message": "Added 'prepend' method to Filesystem.", "backport": null},
{"message": "Added 'reduce' collection to Collection, and 'min' and 'max' to Eloquent Collection.", "backport": null}
{"message": "Added 'reduce' collection to Collection, and 'min' and 'max' to Eloquent Collection.", "backport": null},
{"message": "Added 'firstOrCreate' and 'firstOrNew' methods to Eloquent model.", "backport": null}
]
}

0 comments on commit fce86bc

Please sign in to comment.