1

I often need to perform this query:

$Op = JobCardOp::where([
        ['JobCardNum', '=', $JobCardNum ],
        ['OpNum', '=', $OpNum ]
        ])->first();

So rather than writing this out every time I want a function like:

 public function getOp($JobCardNum, $OpNum)
{
    $Op = JobCardOp::where([
        ['JobCardNum', '=', $JobCardNum ],
        ['OpNum', '=', $OpNum ]
        ])->first();
    return $Op;
}

That I can call in my controller. Where should I define my function, at the moment the I only need it in one controller but I may need it an another if thats possible. Any help appreciated.

2 Answers 2

3

You could put this method on your Model if you wanted to as a static function.

public static function getOp($cardNum, $opNum)
{
    return static::where([
        ['JobCardNum', '=', $cardNum],
        ['OpNum', '=', $opNum]
    ])->first();
}

// controller

$res = YourModel::getOp($cardNum, $opNum);

Or add a query scope to the model

public function scopeGetOp($query, $cardNum, $opNum)
{
    return $query->where([
        ['JobCardNum', '=', $cardNum],
        ['OpNum', '=', $opNum]
    ]);
}

// controller

$res = YourModel::with(...)->getOp($cardNum, $opNum)->first();

Kinda depends how you want to use it.

Sign up to request clarification or add additional context in comments.

1 Comment

Scopes are definitely the way to go. Let's you continue your query if necessary.
3

You may define your function in JobCardOpt model as static:

public static function getOp($JobCardNum, $OpNum)
{
    $Op = static::where([
        ['JobCardNum', '=', $JobCardNum],
        ['OpNum', '=', $OpNum]
    ])->first();
    return $Op;
}

And use it like this in your controllers:

$jobCardOpt = JobCardOpt::getOp(1, 2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.