1

I would like to use the create method with camelCase named variables, something like this:

$review = Review::create((request()->validate([
            'userId' => 'required',
            'movieId' => 'required',
            'title' => 'required',
            'review' => 'required'
        ])));

The problem is that the table 'reviews' has user_id, and movie_id column names, and I get an SQL error. Is there a way to change this in Review model?

Zoran
  • 11
  • 1
  • I think you should separate the validation from create. – Rouhollah Mazarei Sep 09 '21 at 10:04
  • look at this https://stackoverflow.com/questions/25559558/how-can-i-access-attributes-using-camel-case – Vahe Shak Sep 09 '21 at 10:04
  • Why would you want that? Not following the Laravel guidelines makes everything harder. – Gert B. Sep 09 '21 at 10:45
  • @GertB. I would like that frontend api call to laravel has camelCase formatting. – Zoran Sep 09 '21 at 15:13
  • @Zoran That makes no sense. Laravel uses snake case for database columns by default. It is possible to change that, but that means you have to change the default way of handeling things, I think you will get a lot of errors while building the application, and you will need to write a lot of extra code. And only because you want to use camelcase. Other developers will also expect snale_case when working with Laravel. That makes it harder to maintain. – Gert B. Sep 10 '21 at 06:09

1 Answers1

0

I dont know why you need that changing default behavior but you can change this on models boot method and on creating function.You need to change the keys to lower case and map there.

public static function boot()
    {
        parent::boot();

        self::creating(function($model){
            // ... code here for your key maps before creation
        });

        self::created(function($model){
         
        });

        self::updating(function($model){
          
        });

        self::updated(function($model){
            // ... code here
        });

        self::deleting(function($model){
           
        });

        self::deleted(function($model){
           
        });
    }
atikur rahman
  • 503
  • 4
  • 15