'Laravel: model instance value is not quoted at method `save()`
I scrape data of the site https://news.ycombinator.com/news?p=1
Some title contain commas, eg.: Lorinda Cherry, author of dc, bc, eqn has died
So, when I make to save the model (as part of the Laravel CLI command) into DB there is an error.
The code:
try {
$news = new News;
$news->link = $item['link'] ;
$news->title = $item['title'] ;
$news->date = explode('T', $item['date'] )[0];
$news->points = $item['points'];
$news->save();
} catch (Exception $e ){
$this->error($e->getMessage());
}
Error:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '
763 ' for column 'points' at row 1 (SQL: insert into `news` (`link`, `title`, `date`,
`points`, `updated_at`, `created_at`) values (https://ncwit.org/profile/lorindacherry/,
Lorinda Cherry, author of dc, bc, eqn has died, 2022-02-15,
763 , 2022-02-16 11:37:39, 2022-02-16 11:37:39))
Obviously the value Lorinda Cherry, author of dc, bc, eqn has died is not quoted at method save() as the Laravel model item and therefore its content gets mixed with another query parameter...
Why is that in Laravel ?
How to fix ?
Solution 1:[1]
you are trying to save string in points column where column is integer type Thanks
Solution 2:[2]
Try this:
$news->title = '\'' . $item['title'] . '\'';
Solution 3:[3]
Your problem in Incorrect integer value
So, you can cast the point value:
$news->points = (int) $item['points'];
Solution 4:[4]
Alternatively, you can use validation to know your errors and on your code the request['points'] is not integer you are trying to save something that is not integer on your database you should either change the data type on your database to string or you should submit integer data to your endpoint. before saving something to your database you should validate the data i highly recommend
$validatedData = $request->validate([
'link'=>'required|url',
'title' => 'required|string|max:255',
'date' => 'required|date',
'points'=>'required|numeric'
]);
News::create($validatedData);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ajay Kumar |
| Solution 2 | Agustín Tamayo Quiñones |
| Solution 3 | Hicham AIT TALGHALIT |
| Solution 4 | henok tesfu |
