Skip to content

Instantly share code, notes, and snippets.

@sydgren
Last active July 24, 2017 20:00
Show Gist options
  • Save sydgren/46bb222bd7aa6cb166f989af290d58c3 to your computer and use it in GitHub Desktop.
Save sydgren/46bb222bd7aa6cb166f989af290d58c3 to your computer and use it in GitHub Desktop.
Handling model actions in a helper class? Sure, why not
<?php
namespace Doggo\Http\Controllers;
use Doggo\Models\Customer;
use Doggo\Helpers\ModelHelper;
use Illuminate\Http\Request;
class CustomerController extends Controller
{
public function index()
{
return view('customers.index');
}
public function store(Request $request)
{
return ModelHelper::create(Customer::class, $request->all());
}
public function update(Request $request, Customer $customer)
{
return ModelHelper::fill($customer, $request->all(), $save = true);
}
public function destroy(Customer $customer)
{
$customer->delete();
}
}
<?php
namespace Doggo\Helpers;
use Doggo\Traits\Validatable;
class ModelHelper
{
public static function create($model, array $attributes = [])
{
$instance = static::make($model, $attributes);
$instance->save();
return $instance;
}
public static function make($model, array $attributes = [])
{
return static::fill(new $model, $attributes);
}
public static function fill($instance, array $attributes = [], $save = false)
{
if (in_array(Validatable::class, class_uses_recursive($instance))) {
$instance->validate($attributes);
}
$instance->fill($attributes);
if ($save) {
$instance->save();
}
return $instance;
}
}
<?php
namespace Doggo\Traits;
use Illuminate\Validation\ValidationException;
trait Validatable
{
public function validate(array $attributes = null)
{
if (is_null($attributes)) {
$attributes = $this->getAttributes();
}
$validator = validator(
array_intersect_key($attributes, array_flip(array_keys($this->rules()))),
$this->rules()
);
if ($validator->fails()) {
throw new ValidationException($validator);
}
}
/** Override this */
public function rules()
{
return [];
}
public function isValid()
{
try {
$this->validate();
return true;
} catch (\Exception $e) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment