koalaok
koalaok

Reputation: 5740

Laravel apply method concatenation conditionally

By Looking at this code:

if($status == 'processed'){
    DB::connection('mydb')
                            ->table('logs')
                            ->where('id', $id)
                            ->update(array('status' => $status));
}else{
   DB::connection('mydb')
                            ->table('logs')
                            ->where('id', $id)
                            ->where('id2', $id2)
                            ->update(array('status' => $status));
}

The semantic of the code doesn't make much sense since it's an extract from a bigger file. Any way I'm focusing on how to concatenate more methods after a given condition like above

if(A)
    DB->method1()->method2()
else  
    DB->method1()->method3()->method2()

Any idea on how to write this in a more elegant way?

Thanks

Upvotes: 0

Views: 43

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219946

You can add a where clause to the same query object:

$query = DB::connection('mydb')->table('logs')->where('id', $id);

if ($status != 'processed') {
    $query->where('id2', $id2);
}

$query->update(['status' => $status]);

Upvotes: 2

Related Questions