Finalized many to many relationship

This commit is contained in:
2021-09-05 02:51:33 +02:00
parent f4c030934a
commit d1d2198ef5
7 changed files with 77 additions and 35 deletions

View File

@@ -37,6 +37,6 @@ class BeerController extends Controller
$beer->save();
return redirect('/profile');
return back()->with('success', 'Beer added!');
}
}

View File

@@ -33,7 +33,7 @@ class BeerListController extends Controller
$list->save();
return redirect('/profile');
return redirect("/list/" . $list->id);
}
public function addItem(Request $request, $id)
@@ -41,8 +41,8 @@ class BeerListController extends Controller
$beerId = $request->beer;
$list = BeerList::findOrFail($id);
// $list->beer()->attach($beerId);
$list->beer()->attach($beerId);
dd($list->beer());
return redirect("/list/" . $list->id);
}
}

View File

@@ -11,6 +11,6 @@ class Beer extends Model
public function list()
{
return $this->belongsToMany(BeerList::class, 'beer_list_pivot', 'list_id', 'beer_id');
return $this->belongsToMany(BeerList::class, 'beer_list_pivot', 'beer_id', 'list_id');
}
}

View File

@@ -21,6 +21,7 @@ class BeerList extends Model
public function beer()
{
return $this->belongsToMany(Beer::class, 'beer_list_pivot', 'beer_id', 'list_id');
return $this->belongsToMany(Beer::class, 'beer_list_pivot', 'list_id', 'beer_id')
->withTimestamps();
}
}

View File

@@ -16,7 +16,8 @@ class BeerListPivot extends Migration
Schema::create('beer_list_pivot', function (Blueprint $table) {
$table->id();
$table->foreignId('beer_id')->constrained();
$table->foreignId('list_id')->constrained();
$table->foreignId('list_id')->constrained('beer_lists');
$table->timestamps();
});
}

View File

@@ -23,7 +23,10 @@
<label for="review">
Review
</label>
<textarea name="review" style="resize:none"></textarea><
<button type="submit">Add Beer</button>
<textarea name="review" style="resize:none"></textarea>
< <button type="submit">Add Beer</button>
</form>
@if (session()->has('success'))
<p class="text-green-400">{{ session()->get('success') }}</p>
@endif
@endsection

View File

@@ -3,7 +3,7 @@
@section('content')
{{ $list->title }}
<form method="POST" action="{{ route('list.additem', $list->id) }}">
<form method="POST" action="{{ route('list.additem', $list->id) }}">
@csrf
<select name="beer">
<option hidden>
@@ -26,8 +26,45 @@
<button type="submit">
Add beer
</button>
</form>
<a href="{{ route('beer.create') }}">
</form>
<table class="border-2 border-black text-center my-10">
<tr>
<th class="px-2">
Beer
</th>
<th class="px-2">
Rating
</th>
<th class="px-2">
Country
</th>
<th class="px-2">
Type
</th>
</tr>
@foreach ($list->beer as $beer)
<tr>
<td>
{{ $beer->beer }}
</td>
<td>
{{ $beer->rating }}
</td>
<td>
{{ $beer->country }}
</td>
<td>
{{ $beer->type }}
</td>
</tr>
@endforeach
</table>
<a href="{{ route('beer.create') }}">
Can't find your beer?
</a>
</a>
@endsection