I have two tables - Animals and AnimalPhotos. I want to upload images and store them in the AnimalPhotos table. There is a One-to-Many relationship between the tables.
My AnimalPhotoController.php store method looks like this:
public function store(Request $request)
{
$attributes = request()->validate([
'name' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'title' => 'required|string',
'alt' => 'nullable|string',
'caption' => 'nullable|string'
]);
$name = $request->file('name')->getClientOriginalName();
$imageName = date('YmdHis') . $name;
$request->file('name')->storeAs(
'photos', $imageName
);
$request->user()->animalPhotos()->create($attributes);
return redirect('/animals');
}
At the minute it doesn't work because I'm not sure how to store it. I started learning Laravel last year but had about a 6 month gap so I've forgotten a lot. I've looked at the old projects I've tried and in those when I have had a One-To-Many relationship I've put a function on the main table like this (this was for a Books app, so it was Author.php):
public function addBook($title, $year, $series_id)
{
return $this->books()->create(compact('title', 'year', 'series_id'));
}
and then the store method on the AuthorBooksController was:
public function store(Request $request, Author $author)
{
$title = $request->input('title');
$year = $request->input('year');
$series_id = $request->input('series_id');
$author->addBook($title, $year, $series_id);
return redirect($author->path());
}
I don't remember why I did it this way but is this the correct way of doing it and should I be replicating this for my animal photos? Thanks