Search code examples
phplaravellaravel-5eloquent

Check if column exist in Laravel model's table and then apply condition


Current Situation : We are creating new database for new registration.

Problem : If any changes done in database migration we need to handle it for previously created database. Or run that migration for each previously created database.

If we run migration for each database no problem.

Question : how to check database table has column for which we are applying condition in query.

Currently I need to fire two queries first for first row and check the existence of that column and then apply condition in where clause. like below

$firstRow = Model::first();
if(isset($firstRow->is_splited)){
    $records = Model::where('is_splited',0)->get(); // this will give error if I don't check column existence for previously created database. 
}else{
    $records = Model::all();
}

Is there any way to achieve in one query. Or any better way to do it ?


Thanks for your time and suggestion.


Solution

  • @DigitalDrifter gave an idea to use Schema class so I just tried like this

    I Include Schema class

    use Illuminate\Support\Facades\Schema;
    

    And check column by using Schema class, and it also works

    $isColExist = Schema::connection("connection_name")->hasColumn('table_name','is_splited');
    $q = Acquire::with("block");
    if($isColExist){
        $q->where('is_splited',0);
    }
    $records = $q->get();