Method for get id through value - Laravel

10,270

Method

public function getId($model, $table, $value) {
    return $model::where($table, $value)->first()->id;
}

Usage

$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.

Share:
10,270

Related videos on Youtube

Mer
Author by

Mer

Updated on July 05, 2022

Comments

  • Mer
    Mer almost 2 years

    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!