Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 60 lines (47 sloc) 1.86 KB

Foobooks: One to Many

The following is a rough outline of the modifications I'll make to Foobooks during Week 13's lectures.

This should not be considered a stand-alone document; for full details please refer to the lecture video and the Foobooks code source.

Author dropdown

To associate Authors with Books we'll use a dropdown filled with authors. I'll start by showing this in the Add a book feature, and later add it to the Edit a book feature.

# BookController.php
public function create($id)
{
    # Get data for authors in alphabetical order by last name
    $authors = Author::orderBy('last_name')->select(['id', 'first_name', 'last_name'])->get();

    return view('book.edit')->with([
        'authors' => $authors
    ]);
}

Construct the dropdown (<select>) in the view using this data:

<label for='author_id'>* Author</label>
<select name='author_id'>
    <option value=''>Choose one...</option>
    @foreach($authors as $author)
        <option value='{{ $author->id }}' {{ (old('author_id') == $author->id) ? 'selected' : '' }}>{{ $author->first_name.' '.$author->last_name }}</option>
    @endforeach
</select>
@include('modules.field-error', ['field' => 'author_id'])

Update the BookController@store method to also save the author details about the book.

One way to do this:

$author = Author::find($request->author_id);
$book->author()->associate($author);

Or, just manually specify the author_id since we already have it in the request. Saves us a trip to the database to fetch the Author object.

$book->author_id = $request->author_id;

Validation

$this->validate($request, [
    'title' => 'required|min:3',
    'author_id' => 'required', # <---- Validate author dropdown
    'published' => 'required|min:4|numeric',
    'purchase_link' => 'required|url',
    'cover' => 'required|url',
]);
You can’t perform that action at this time.