lundi 15 octobre 2018

Laravel 5.4 store Many to Many relationship in database

I have 2 models

  • ImageRequest
  • RequestType

1 ImageRequest can have Many RequestTypes and 1 RequestType can have Many ImageRequests.

I translated this like this in my models:

ImageRequest Model:

/**
 * Get the Request Types for an image request.
 */
public function requestTypes()
{
    return $this->hasMany('App\RequestType');
}

RequestType Model:

/**
 * Get the Image Requests for a Request Type.
 */
public function imageRequests()
{
    return $this->hasMany('App\ImageRequest');
}

My migration for the image_requests table:

$table->unsignedInteger('request_type_id')->nullable();
$table->foreign('request_type_id')->references('id')->on('request_types');

In my form I have multiple checkboxes to select the RequestTypes when creating a new ImageRequest like this:

@foreach($requestTypes as $requestType)
    
    
    <br>
@endforeach

I have a function in my service to store the ImageRequest that looks like this:

public function storeImageRequest(StoreImageRequestRequest $request)
{
    return Auth::user()->imageRequests()->save(new ImageRequest($request->all()));
}

This works great but it only stores the last "request_type_id" selected. It can't store all request_type_id's.

How can I store multiple request_type_id's?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire