I am relatively new to Laravel and coding in general. I am trying to use Eloquent and to pass data from my form into a MySQL database. I can "submit" without any errors but don't see the data in the table. I feel like my code is getting messier as I am trying to figure this out and I would love a review of my code. I've tried several different ways of doing this by reading through tutorials, books and reviewing other people's code.
Route
Route::post('submit', function (Request $request) {
$data = $request->validate([
'title' => 'required|max:255',
'category' => 'required|max:255',
'content' => 'required|max:900',
]);
return redirect('submit');
});
Controller
<?php
public function store(Request $request)
{
Post::create([
'title' => $request->title,
'category' => $request->category,
'content' => $request->content,
]);
return redirect('views.submit');
}
View/Blade
<div>
<form action='' method='post'>
@csrf
<p><label>Title</label><br/>
<input type='text' name='title' value=''><?php if (isset($error)) {
echo $_POST['title'];
}?></p>
<p><label>Category</label><br/>
<textarea name='category' cols='60' rows='10'><?php if (isset($error)) {
echo $_POST['category'];
}?></textarea></p>
<p><label>Content</label><br/>
<textarea name='content' cols='60' rows='10'><?php if (isset($error)) {
echo $_POST['content'];
}?></textarea></p>
<p><input type='submit' name='submit' value='Submit'></p>
</form>
</div>
I'm expecting this to pass data to my table named "blogs."
So I finally solved this after making several changes.
The first thing I did was moved my controller to /app/books.php
I simplified the code to the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class books extends Model
{
protected $fillable = [
'title',
'author',
'category',
];
}
I then modified the route to NOT include the redirect:
Route::post('/submitbook', function (Request $request) {
$data = $request->validate([
'title' => 'required|max:255',
'author' => 'required|max:255',
'category' => 'required|max:255',
]);
Perhaps the biggest resolution happened by a fluke. I was working on a separate issue and had to clear my known_hosts file and everything worked after.