简体   繁体   中英

How to get Value from Selected Option in Laravel from 2 different table in database

I want to get the Value of it to insert it into my Games table in database. But I have to show the name of genre from the Genres table in database.

View:

<select name="genreid">
                    @foreach($genres as $genre)
                        <option value="{{ $genre->genreid }}"> {{ $genre->genre }}</option>
                        @endforeach
                </select>

Controller:

public function insertgame(Request $request){

        $this -> validate($request, array(
                'gamename' => 'required|min:3',
                'price' => 'required|int|min:1',
                'genre' => 'required',
                'releaseddate' => 'required|date',
                'picture' => 'required|mimes:jpeg,jpg,png,gif'
        ));


        $gamename = $request->input('gamename');
        $genreid = $request->input('genreid');
        $price = $request->input('price');
        $releaseddate = Carbon::parse($request->input('releaseddate'));
        $picture = $request->file('picture')->getClientOriginalName();

        $data=array('gamename' => $gamename, 'genreid'=>$genreid, 'price'=>$price,'releaseddate'=>$releaseddate,'picture'=>$picture );

        DB::table('games')->insert($data);

        return redirect('managegame');

    }

You've said it works for you if you use this HTML:

<select name="genre">
    <option selected disabled>Choose one</option>
    <option value="FPS">FPS</option>
    <option value="Action">Sports</option>
    <option value="Action">Action</option>
    <option value="Racing">Racing</option>
    <option value="Simulation">Simulation</option>
</select>

In this case, to use proper data format, change this:

<option value="{{ $genre->genreid }}">{{ $genre->genre }}</option>

To:

<option value="{{ $genre->genre }}">{{ $genre->genre }}</option>

Do something like this

@foreach($game->genres as $genre)
{
  <option value='{{$genre->id}}' {{$game->genre ==$genre->id ? 'selected' :' '> {{$genre->name}} </option>
 }

I've found the answer!

I just changed

'genre' => 'required',

to

'genreid' => 'integer|required',

LOL Thanks all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM