Check if column exist in table
Import schema

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
if (Schema::hasColumn($table, 'deleted_at')){ 
   Query 1
}else{
   Query 2
}
This is useful if we use one query in multiple resources but there is some differences in table structure and we need to use this column in condition: for example:

 if (Schema::hasColumn($table, 'deleted_at')){
            $query = "SELECT
                $columns_str
                -- c1.order_priority,
                (
                    SELECT
                        Count(c2.id)
                    FROM
                        $table AS c2
                    WHERE
                        c2.parent_id = c1.id
                )
                AS children_count
            FROM
                $table AS c1
            WHERE deleted_at IS NULL
                ORDER BY ".($order_priority ? 'order_priority' : 'id')." DESC";
        }else{
            $query = "SELECT
                $columns_str
                -- c1.order_priority,
                (
                    SELECT
                        Count(c2.id)
                    FROM
                        $table AS c2
                    WHERE
                        c2.parent_id = c1.id
                )
                AS children_count
            FROM
                $table AS c1
                ORDER BY ".($order_priority ? 'order_priority' : 'id')." DESC";
        }
We use
   WHERE deleted_at IS NULL
where we have deleted_at column
by Luka Tatarishvili
3 years ago
Laravel
database
0
Pro tip: use ```triple backticks around text``` to write in code fences