Above your $book = new Book(); line, what does dd($request->all()); return?
Jul 17, 2023
16
Level 2
Laravel 10 - Model::save not working
I'm building a book library management system. In my BookController, when doing $book->save() or $book->saveorFail() it returns successful but no records are written to the database. Also, I'm not receiving any errors or notifications.
Here's my code:
In migration:
Schema::create('books', static function (Blueprint $table) {
$table->id();
$table->string('title');
$table->longText('content');
$table->decimal('price');
$table->string('year_published', 4);
$table->string('cover')->nullable();
$table->integer('author_id');
$table->timestamps();
});
in Model:
class Book extends Model
{
use HasFactory;
protected $primaryKey = 'id';
protected $fillable = [
'title',
'content',
'price',
'year_published',
'cover',
'author_id',
];
}
In my controller
public function store(Request $request)
{
// try
// {
$validator = Validator::make($request->all(), [
'title' => 'required|unique:books|max:255',
// 'cover' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'content' => 'required|max:1000',
'price' => 'required',
'year_published' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
$image = null;
$coverName = '';
if ($request->file('cover'))
{
$image = $request->file('cover');
$coverName = time().'.'.$image->getClientOriginalExtension();
}
$book = new Book();
$book->title = $request['title'];
$book->content = $request['content'];
$book->price = $request['price'];
$book->year_published = $request['year_published'];
// $book->cover = $coverName;
$book->author_id = random_int(1, 10);
if ($book->saveOrFail()) {
if ($request->hasFile('cover')) {
$destinationPath = public_path('/assets/books/' . $book->id . '/');
// If directory is not there, create it.
if (!is_dir($destinationPath))
{
if (!mkdir((string)$destinationPath) && !is_dir((string)$destinationPath)) {
throw new \RuntimeException(sprintf('An error occurred when creating directory "%s".', (string)$destinationPath));
}
chmod((string)$destinationPath, 0755);
}
// If the directory has images , clean up first before upload.
if (!empty(scandir($destinationPath)))
{
File::cleanDirectory($destinationPath);
}
// directory is empty, upload image, update image name in database.
$image->move($destinationPath, $coverName);
}
return redirect()->back()->with('success', 'Book added successfully');
}
// } catch(\Exception $ex) {
// Log::error($ex->getMessage());
// }
}
Any thoughts about what I'm not doing right and/or how to fix?
Please or to participate in this conversation.