SarahS's avatar
Level 12

Updating a BelongsTo table

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

0 likes
2 replies
gokulkhatiwada's avatar
Level 2
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'
       ]);

	$animal = Animal::findorfail($request->animal_id);
   
        $name = $request->file('name')->getClientOriginalName();
        $imageName =  date('YmdHis') . $name;
        $request->file('name')->storeAs(
            'photos', $imageName
        );

        $animal->animalPhotos()->create($attributes);

        return redirect('/animals');
    }

your animal has photos not user.

SarahS's avatar
Level 12

Yes you're right! I passed in the Animal too from the form. I just need to work out how to add the new name I created (imageName) to be used in the $attributes instead of the Request $name.

Please or to participate in this conversation.