Reputation: 93
Through this query I find a element in a database by value and take the id:
Model::where($table,'=',$value)->first()->id;
But I need to create a method, because I use this code with other models; a possible example:
public function getId($model,$table,$value) {
...
}
How can I do?
Thanks!
Upvotes: 2
Views: 20840
Reputation: 10087
I would create a Trait
<?php
namespace App\Models\Traits;
trait GetIdByNameTrait
{
public function scopeGetIdByName($query, $name)
{
return $query->where('name', $name)->first()->id;
}
}
The models should use it:
use Traits\GetIdByNameTrait;
Then you can use this everywhere;
$id = Model::getIdByName($value);
Upvotes: 0
Reputation: 778
public function getId($model, $table, $value) {
return $model::where($table, $value)->first()->id;
}
$id = getId('App\User', 'name', 'John Doe');
From your code, it looks like you have this as a class method. Instead, you could create this as a global helper so you can access it anywhere.
Upvotes: 5