1

For example, I have my codes.

$news = new News();
$news->title = 'hello world';
$new->user = $user_id,
$news->urlcc = DB::raw('crc32("'.$args['newsShortUrlInput'].'")');
$news->save();
$news->refresh();

Here with attribute $news->urlcc comes from user input after using mysql function crc32(); For the SQL injection issue, above codes not safe.

So, my question is how to bind the parameters in DB::raw() with Laravel model something like below.

$news->urlcc = DB::raw('crc32(:newsShortUrlInput)', ['newsShortUrlInput' => $args['newsShortUrlInput]);

Thanks,

jarlh
  • 42,561
  • 8
  • 45
  • 63
Johnson
  • 67
  • 1
  • 10
  • Does this answer your question? [How to bind parameters to a raw DB query in Laravel that's used on a model?](https://stackoverflow.com/questions/20864872/how-to-bind-parameters-to-a-raw-db-query-in-laravel-thats-used-on-a-model) – apokryfos Jan 07 '22 at 06:54
  • No, that is doing Model select, I am trying to create record using Laravel Models. – Johnson Jan 07 '22 at 07:00
  • This answers your question: https://stackoverflow.com/a/20873009/7698734 – Hassaan Ali Jan 07 '22 at 07:07
  • That's not possible then as far as I know. The bindings can't be passed in DB::raw and you don't generally don't have access to the builder object that is created to save the model to add bindings that way. For this particular case you can use PHPs [crc32](https://www.php.net/manual/en/function.crc32.php) instead though. – apokryfos Jan 07 '22 at 07:18
  • All the suggestions which show me how to bind parameters in select statement doesn't match with my condition. My case is trying to create new Laravel model. I found one solution see below. Thanks – Johnson Jan 07 '22 at 07:36

1 Answers1

0

I found one solution, not sure it is right or perfect solution.

In News model class to rewrite setAttribute, see below.

public function setUrlcrcAttribute($shortUrl)
{
    $this->attributes['urlcrc'] = $this->getConnection()->select('select crc32(?) as urlcrc', [$shortUrl])[0]->urlcrc;
}

In your service class to create a new model like below.

$news = new News();
$news->title = 'hello world';
$new->user = $user_id,
$news->urlcrc = $args['newsShortUrlInput']; // Laravel model will try to build the real attribute urlcrc
$news->save();
$news->refresh();

It works to me, but not sure this is perfect solution or not.

Johnson
  • 67
  • 1
  • 10