asdasdsa
2 months ago
449
10
Eloquent

How to update relationship?

Posted 2 months ago by asdasdsa

Hi!

I have a a Game model and a Url model.

The Game model has a relation to Url model like this:

    public function urls(){
        return $this->hasMany(Url::class);
    }

The Url model has a relation to Game model like this:

    public function game(){
        return $this->belongsTo(Game::class);
    }

With this current setup (dont know if it is the best) can i store multipel urls for a specific game. But now comes the problem, i would like to add, edit and delete urls for games... And i have no idea on how to do this. I have a edit page for the games - would be nice to edit the urls there as well.

I have been trying to do something like this:

GameController.php

public function update(){
	$game->urls()->update($request->get('url'));
}

And for my view

        @forelse($game->urls as $url)
        <div class="">
            <label for="url" class="">{{ $url->host }}</label>
            <div class="">
                <input id="url"
                type="text"
                class="@error('url') is-invalid @enderror"
                name="url[{{ $url->host }}]"
                value="{{ old('url->url', $url->url) }}">

                @error('url')
                <span class="" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
                @enderror
            </div>
        </div>
        @empty
            No links
        @endforelse

        <div class="">
            <label for="url_host" class="">Add link</label>
            <div class="">
                <input id="url_host"
                type="text"
                class="@error('url_host') is-invalid @enderror"
                name="url_host"
                value="{{ old('urls->url') }}" placeholder="ex: wikipedia_url">
                @error('url_host')
                <span class="" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
                @enderror

                <input id="new_url"
                type="text"
                class="@error('new_url') is-invalid @enderror"
                name="new_url"
                value="{{ old('urls->url') }}" placeholder="http://en.wikipedia.org/xxx">

                @error('new_url')
                <span class="" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
                @enderror
            </div>
        </div>

Please sign in or create an account to participate in this conversation.