Mer
Mer

Reputation: 93

Method for get id through value - Laravel

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

Answers (2)

António Almeida
António Almeida

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

Saeed Prez
Saeed Prez

Reputation: 778

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.

Upvotes: 5

Related Questions