Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
Niklesh Raut Avatar asked Aug 06 '18 08:08

Niklesh Raut


3 Answers

@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();
like image 146
Niklesh Raut Avatar answered Oct 20 '22 18:10

Niklesh Raut


Updated solution working in 5.8

if ($object->getConnection()
           ->getSchemaBuilder()
           ->hasColumn($object->getTable(), 'column_name')) {
    // required update here
}

This solution only requires an $object and a 'column_name' to work. The connection and table names are derived from the object itself.

like image 30
wheelmaker Avatar answered Oct 20 '22 18:10

wheelmaker


Late here but a simple and quick solution

    if (Schema::hasColumn('flights', 'departure_time')){
        // do something
      }
like image 40
Abrar Ahmad Avatar answered Oct 20 '22 18:10

Abrar Ahmad