Skip to content
Advertisement

Laravel PUT relationship

Fiddling with Laravel and coming from Symfony, I’m trying to replicate some code. I’m trying to PUT a Suggestion model (overwritting anything, even relationships) and wanted to know the proper way to overwrite the model. Since tags attribute in fillable doesn’t exist, I certainly get an error (Undefined column: 7 ERROR: column "tags" of relation "suggestions" does not exist). Suggestions and tags both have their own tables and a pivot table that contains two foreign keys to both tables id.

Request & Response :

{
"id":2,
"content":"Magni.",
"tags":[{"id":13,"name":"MediumAquaMarine"}]
}
{
"id":2,
"content":"Magni.",
"tags":[{"id":10,"name":"Navy"},{"id":13,"name":"MediumAquaMarine"}]
}
public function update(Request $request, Suggestion $suggestion)
{
    $validator = Validator::make($request->all(), [
        'content' => 'required',
        'tags.id' => 'numeric',
    ]);

    if ($validator->fails()) {
        return response()->json($validator->messages(), Response::HTTP_BAD_REQUEST);
    }

    $suggestion->fill($request->only($suggestion->getFillable()))->save();

    return new SuggestionResource($suggestion);
}

class Suggestion extends Model
{
    use HasFactory;

    protected $fillable = ['content', 'tags'];

    protected $with = ['tags'];

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'suggestions_tags')->withTimestamps();
    }
}

class Tag extends Model
{
    use HasFactory;

    protected $hidden = ['pivot'];

    public function suggestions()
    {
        return $this->belongsToMany(Suggestion::class, 'suggestions_tags')->withTimestamps();
    }
}

Advertisement

Answer

You could just pass an array of IDs for tags instead of the whole object.

Do:

"tags":[10, 13]

Instead of:

"tags":[{"id":10,"name":"Navy"},{"id":13,"name":"MediumAquaMarine"}]

Change the validation rules accordingly and then you can remove tags from $fillable and do something like:

$suggestion->update($request->validated());

$suggestion->tags()->sync($request->tags);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement