How to know if a particular column exists in a table in Laravel?

Asked

Viewed 403 times

2

I wonder if there is any way to know if a column exists or not in the Laravel.

For example, I want to sort data from the query string. If the value "column" exists in the table, then I sort by this field.

 $coluna = Input::get('coluna');

 if (se_a_coluna_existe_na_tabela('usuarios', $coluna))
 {
     $query->orderBy($coluna);
 }
  • 3

    Back to the dark side of the force :( :D

  • 1

    No, actually I am leaving PHP gradually. I already downloaded the full Visual Studio and I will install it on my home PC. :)

  • 1

    @bigown we all know that in the end the dark side loses :D

  • 1

    @Guilhermelautert not until the last episode :P

  • In this case, it would be an incorrect parameter, I believe the best way is to try to order, and capture the exception, if there is no column (If you do not want the user to know that you screwed up...)

  • @mauhumor well, it’s a good idea. I can also catch the QueryException and bring a message to the user

  • Who gave the negative, could inform what is wrong with the question?

Show 2 more comments

1 answer

3


It’s not that hard, you can just use the following code

if(Schema::hasColumn('users', 'email')) ; //verifica se a tabela users tem a coluna email
{
    $query->orderBy($coluna);
}

ready!

If you have any questions, try to have a look at the documentation of the Laravel.

https://laravel.com/docs/5.0/schema#checking-Existence

  • Thank you Dannis!

  • You’re welcome Wallace! Anything, just call =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.