samedi 24 novembre 2018

Laravel. Two tables in relationship, selection of many photos

I have two tables: Calendar, and Photo in relationship one calendar's event to many photos.

I would like to add many photos when creating the event. Currently, I can only have one, on a one-to-one basis.

My code: Calendar model relation with Photo:

public function photos()
   {
       return $this->hasMany(Photo::class);   
   }

Photo model relation with Calendar:

public function calendar()
   {
       return $this->belongsTo(Calendar::class, 'calendar_id');
   }

it's ok and it works.

Fragment of create.blade.php view:

<div class="card-body">
<form action="" method="POST"
                              enctype="multipart/form-data">
     <input type="hidden" name="_token" value=""/>
<div class="form-group">
     <label for="photo">Photo:</label> <select class="form-control" name="photo"> 
         @foreach($photos as $photo)
             <option value=""></option>
         @endforeach
         </select>
</div>
<div class="form-group">
     <label for="header">Header</label> <input type="text" class="form-control" name="header"/></div>
<div class="form-group">
     <label for="description">Description</label><input type="text" class="form-control" name="description"/></div>
<div class="form-group">
     <label for="date">Date</label> <input type="date" class="form-control" name="date"/></div>
     <input type="submit" value="Create" class="btn btn-primary"/>
</form>
</div>

For this moment I have classic select list where can I choose only one option.

Calendar controller code (function create and store):

public function create()
    {
        $photos = Photo::all();
        return view('pages.calendar.create', [
            "photos" => $photos
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'header' => 'required|max:255',
            'description' => 'required',
            'date' => 'required',
        ]);

        $calendar = new Calendar();
        $calendar->header = $request->input('header');
        $calendar->description = $request->input('description');
        $calendar->date = $request->input('date');
        $calendar->save();

        $photo = Photo::find($request->input('photo'));
        if($photo !== null) {
            $photo->calendar_id = $calendar->id;
            $photo->save();
        }
       return redirect()->action('CalendarController@clist');
   }

How can I change this fragment of code to multistore photos:

$photo = Photo::find($request->input('photo'));
if($photo !== null) {
     $photo->calendar_id = $calendar->id;
     $photo->save();
}

I have calendar_id in Photo table (fereign key). Thanks for any help!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire