PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

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

 January 19, 2022     eloquent, laravel, laravel-5, php     No comments   

Issue

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();


Answered By - Niklesh Raut
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing