(PHP) Eloquent doodles for Laravel


[php]
// Get model by primary key
$myModel = MyModel::find($id);

//Where can use short syntax for equal comparison.
$myModels = MyModel::where(‘someAttribute’, ‘=’, ‘someValue’)->get();
$myModels = MyModel::where(‘someAttribute’, ‘someValue’)->get();

// Delete models
$affectedRows = MyModel::where(‘someAttribute’, ‘someValue’)->delete();

// Select distinct
$distincts = MyModel::distinct()->select(‘someAttribute’)->where(‘someAttribute’, ‘someValue’)->get();

// Select with Limit and offset
$myModels = MyModel::limit(30)->get();
$myModels = MyModel::limit(30)->offset(30)->get();
[/php]

Different ways of getting a single model and checking if it’s there.
[php]

// 1
$model= MyModel::where(‘someAttribute’, $someValue)->get();

if (!$model->isEmpty()) {
$firstModel= $model->first()
}

// 2
try {
$model= MyModel::where(‘someAttribute’, $someValue)->firstOrFail();
// Do stuff with model
} catch (ErrorException $e) {
// Do stuff if it doesn’t exist.
}

// 3
$models = MyModel::where(‘someAttribute’, $someValue)->get(); // Collection of models
$models = MyModel::where(‘someAttribute’, $someValue)->first(); // Single model or null

if (count($models)) {
//Collection: to get the first item
$users->first().

//if you used first() just use the $models
}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *