arrowill12
arrowill12

Reputation: 1804

Multiple queries in laravel scope function

I am attempting to make multiple queries in a scope function in laravel. my code is as follows. the first query executes normally but the second seems to be ignored. what is the correct way to do this?

public function scopeUpdateStatus($query,$oldUser, $newUser, $alias, $env) {

$query->where('db_conn_app_alias_user', $newUser)->where('db_conn_app_alias', $alias)->where('app_instance_environment', $env)->update(array('user_status' => 'active'));
$query->where('db_conn_app_alias_user', $oldUser)->where('db_conn_app_alias', $alias)->where('app_instance_environment', $env)->update(array('user_status' => 'passive'));

return "success";
}

Upvotes: 4

Views: 2969

Answers (3)

Olurotimi Abraham
Olurotimi Abraham

Reputation: 11

A minor edit (reduces overhead) to @merlinpatt answer. You don't need to clone the $query twice. Just once, as you already have the existing/original variable

function scopeSomeName($query) {
    $query_cloned = clone $query;
    $query->whereStuff;
    $query_cloned->whereOtherStuff;
}

Also, there's no need for the with() helper function. Tested it and works as expected.

Upvotes: 0

Merlin -they-them-
Merlin -they-them-

Reputation: 2940

The trick here is to use with (a Laravel helper function) and clone.

function scopeSomeName($query) {
    with(clone $query)->whereStuff;
    with(clone $query)->whereOtherStuff;
}

Upvotes: 1

totymedli
totymedli

Reputation: 31048

This happens because you use the same $query variable in the two updates. You add where()s to the $query in the first update query and then run it, but when you add your where()s in the second update query the where()s from the first query are still there. Because of this your query will return zero result so there is nothing to update. Copy the $query first to a new variable then run the second query in the copied one:

public function scopeUpdateStatus($query, $oldUser, $newUser, $alias, $env) {
    $queryTemp = $query;

    $query->where('db_conn_app_alias_user', $newUser)
        ->where('db_conn_app_alias', $alias)
        ->where('app_instance_environment', $env)
        ->update(array('user_status' => 'active'));

    $queryTemp->where('db_conn_app_alias_user', $oldUser)
        ->where('db_conn_app_alias', $alias)
        ->where('app_instance_environment', $env)
        ->update(array('user_status' => 'passive'));

    return "success";
}

Upvotes: 0

Related Questions