Laravel Inertia js & vue js - php

I am trying to make a delete button for my Laravel 8 app. I got some errors while doing that and don't know how to do it.
My app is about creating training courses for students and for each training course they will get a YouTube video created by an admin and I am trying to add the delete formation function.
That is my controller I tried to create a delete function. My update, create functions work fine but the delete doesn't work and I get the following error message:
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'course' of undefined"
![Error message screenshot][1]
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Inertia\Inertia;
use App\Models\Course;
use App\Models\Episode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Requests\StoreCourseWithEpisodes;
class CourseController extends Controller
{
public function index()
{
$courses = Course::with('user')
->select('courses.*', DB::raw(
'(SELECT COUNT(DISTINCT(user_id))
FROM completions
INNER JOIN episodes ON completions.episode_id = episodes.id
WHERE episodes.course_id = courses.id
) AS participants'
))->addSelect(DB::raw(
'(SELECT SUM(duration)
FROM episodes
WHERE episodes.course_id = courses.id
) AS total_duration'
))
->withCount('episodes')->latest()->paginate(5);
return Inertia::render('Courses/Index', [
'courses' => $courses
]);
}
public function show(int $id)
{
$course = Course::where('id', $id)->with('episodes')->first();
$watched = auth()->user()->episodes;
return Inertia::render('Courses/Show', [
'course' => $course,
'watched' => $watched
]);
}
public function store(StoreCourseWithEpisodes $request)
{
$user_id = \Auth::user()->id;
$course = Course::create($request->all());
foreach($request->input('episodes') as $episode)
{
$episode['course_id'] = $course->id;
Episode::create($episode);
}
return Redirect::route('courses.index')->with('success', 'Félicitations, votre formation a bien été postée.');
}
public function edit(int $id)
{
$course = Course::where('id', $id)->with('episodes')->first();
$this->authorize('update', $course);
return Inertia::render('Courses/Edit', [
'course' => $course
]);
}
public function update(StoreCourseWithEpisodes $request)
{
$course = Course::where('id', $request->id)->first();
$this->authorize('update', $course);
$course->update($request->all());
$course->episodes()->delete();
foreach($request->episodes as $episode) {
$episode['course_id'] = $course->id;
Episode::create($episode);
}
return Redirect::route('courses.index')->with('success', 'Félicitations, votre formation a bien été modifiée.');
}
public function toggleProgress(Request $request)
{
$id = $request->input('episodeId');
$user = auth()->user();
$user->episodes()->toggle($id);
return $user->episodes;
}
public function delete(StoreCourseWithEpisodes $request ,$id)
{
$course = Course::find($id);
$course->episodes()->delete();
// $request->has('id') ?
// Article::find($request->input('id'))->delete() :
// redirect()->back()
// ->with('errors', 'Attentions.');
return Redirect::route('courses.index')->with('success', 'Félicitations, votre formation a bien été supprimer.');
}
}
That is my vue where I have to call my delete function:
<template>
<app-layout>
<template #header>
Liste des formations
</template>
<section class="py-6">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div v-if="$page.flash.success" class="bg-green-200 text-green-600 p-4">
{{ $page.flash.success }}
</div>
<div class="py-3" v-for="course in courses.data" v-bind:key="course.id">
<div class="bg-white rounded shadow p-4">
<div class="text-sm text-gray-500 flex justify-between items-center">
<div>
Mise en ligne par <strong>{{ course.user.name }}</strong> (<span class="text-gray-500 text-sm">{{ course.participants }} participant<span v-if="parseInt(course.participants) > 1 ">s</span>)
</span>
</div>
<span class="block text-sm text-gray-400">{{ course.episodes_count }} épisode<span v-if="course.episodes_count > 1">s</span></span>
</div>
<h1 class="text-3xl">{{ course.title }}</h1>
<span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">
{{ convert(course.total_duration) }}</span>
<div class="text-sm text-gray-500 mt-2">{{ course.description }}</div>
<div class="flex justify-between items-center">
<a :href="'course/' + course.id" class="bg-indigo-700 text-white px-3 py-2 text-sm mt-3 inline-block rounded hover:bg-indigo-500">Voir la formation</a>
<a :href="'courses/edit/' + course.id" v-if="course.update" class="bg-gray-700 text-white px-3 py-2 text-sm mt-3 inline-block rounded hover:bg-gray-500">Editer</a>
<button #click="remove(course.id)"
class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
Supprimer
</button>
</div>
</div>
</div>
<inertia-link :href="link.url" class="text-indigo-700 border-gray-500 p-5" v-for="link in courses.links" v-bind:key="link.label">
<span v-bind:class="{'text-red-700' : link.active}">{{ link.label }}</span>
</inertia-link>
</div>
</section>
</app-layout>
</template>
<script>
import AppLayout from './../../Layouts/AppLayout';
export default {
components: {
AppLayout
},
props: ['courses'],
data() {
return {
courseData: this.courses
}
},
methods: {
remove() {
this.$inertia.delete('/courses/delete/'+ this.courseData.id, this.courseData);
},
// deleteRow(id) {
// this.$inertia.delete('/article/delete/' + id)
// },
convert(timestamps) {
let hours = Math.floor(timestamps / 3600);
let minutes = Math.floor(timestamps / 60) - (hours * 60);
let seconds = timestamps % 60;
return hours.toString().padStart(2, 0) + ':' + minutes.toString().padStart(2, 0) + ':' + seconds.toString().padStart(2, 0);
}
}
}
</script>
[enter image description here][2]
here is my vue with no error but my delete button still does not work
<template>
<app-layout>
<template #header>
Liste des formations
</template>
<section class="py-6">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div v-if="$page.flash.success" class="bg-green-200 text-green-600 p-4">
{{ $page.flash.success }}
</div>
<div class="py-3" v-for="course in courses.data" v-bind:key="course.id">
<div class="bg-white rounded shadow p-4">
<div class="text-sm text-gray-500 flex justify-between items-center">
<div>
Mise en ligne par <strong>{{ course.user.name }}</strong> (<span class="text-gray-500 text-sm">{{ course.participants }} participant<span v-if="parseInt(course.participants) > 1 ">s</span>)
</span>
</div>
<span class="block text-sm text-gray-400">{{ course.episodes_count }} épisode<span v-if="course.episodes_count > 1">s</span></span>
</div>
<h1 class="text-3xl">{{ course.title }}</h1>
<span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">
{{ convert(course.total_duration) }}</span>
<div class="text-sm text-gray-500 mt-2">{{ course.description }}</div>
<div class="flex justify-between items-center">
<a :href="'course/' + course.id" class="bg-indigo-700 text-white px-3 py-2 text-sm mt-3 inline-block rounded hover:bg-indigo-500">Voir la formation</a>
<a :href="'courses/edit/' + course.id" v-if="course.update" class="bg-gray-700 text-white px-3 py-2 text-sm mt-3 inline-block rounded hover:bg-gray-500">Editer</a>
<button #click="remove()"
class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
Supprimer
</button>
</div>
</div>
</div>
</div>
</section>
</app-layout>
</template>
<script>
import AppLayout from './../../Layouts/AppLayout';
export default {
components: {
AppLayout
},
props: ['courses'],
data() {
return {
courseData: this.courses
}
},
methods: {
remove(id) {
this.$inertia.delete('/courses/delete/'+ id);
},
// deleteRow(id) {
// this.$inertia.delete('/article/delete/' + id)
// },
convert(timestamps) {
let hours = Math.floor(timestamps / 3600);
let minutes = Math.floor(timestamps / 60) - (hours * 60);
let seconds = timestamps % 60;
return hours.toString().padStart(2, 0) + ':' + minutes.toString().padStart(2, 0) + ':' + seconds.toString().padStart(2, 0);
}
}
}
</script>
and my controller right here
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Inertia\Inertia;
use App\Models\Course;
use App\Models\Episode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Requests\StoreCourseWithEpisodes;
class CourseController extends Controller
{
public function index()
{
$courses = Course::with('user')
->select('courses.*', DB::raw(
'(SELECT COUNT(DISTINCT(user_id))
FROM completions
INNER JOIN episodes ON completions.episode_id = episodes.id
WHERE episodes.course_id = courses.id
) AS participants'
))->addSelect(DB::raw(
'(SELECT SUM(duration)
FROM episodes
WHERE episodes.course_id = courses.id
) AS total_duration'
))
->withCount('episodes')->latest()->paginate(5);
return Inertia::render('Courses/Index', [
'courses' => $courses
]);
}
public function show(int $id)
{
$course = Course::where('id', $id)->with('episodes')->first();
$watched = auth()->user()->episodes;
return Inertia::render('Courses/Show', [
'course' => $course,
'watched' => $watched
]);
}
public function store(StoreCourseWithEpisodes $request)
{
$user_id = \Auth::user()->id;
$course = Course::create($request->all());
foreach($request->input('episodes') as $episode)
{
$episode['course_id'] = $course->id;
Episode::create($episode);
}
return Redirect::route('courses.index')->with('success', 'Félicitations, votre formation a bien été postée.');
}
public function edit(int $id)
{
$course = Course::where('id', $id)->with('episodes')->first();
$this->authorize('update', $course);
return Inertia::render('Courses/Edit', [
'course' => $course
]);
}
public function update(StoreCourseWithEpisodes $request)
{
$course = Course::where('id', $request->id)->first();
$this->authorize('update', $course);
$course->update($request->all());
$course->episodes()->delete();
foreach($request->episodes as $episode) {
$episode['course_id'] = $course->id;
Episode::create($episode);
}
return Redirect::route('courses.index')->with('success', 'Félicitations, votre formation a bien été modifiée.');
}
public function toggleProgress(Request $request)
{
$id = $request->input('episodeId');
$user = auth()->user();
$user->episodes()->toggle($id);
return $user->episodes;
}
public function delete(StoreCourseWithEpisodes $request ,$id)
{
// dd($id);
Course::find($id)->delete();
// $course->episodes()->delete();
// $request->has('id') ?
// Article::find($request->input('id'))->delete() :
// redirect()->back()
// ->with('errors', 'Attentions.');
return Redirect::route('courses.index')->with('success', 'Félicitations, votre formation a bien été supprimer.');
}
}

Related

post request not working in laravel livewire

hello guys I'm new to laravel and livewire please kindly assist, post request not going through , if i click on the submit nothing is happening, I'm not getting error either, I have added the livewire script in my app.blade.php and it's rendering properly
Post Create form
<div>
<div class="p-4 mx-auto mt-3 bg-gray-100 md:p-8 md:w-4/5 md:mt-0">
<h1 class="mb-3 text-xl font-semibold text-gray-600">New post</h1>
<form wire:submit.prevent="createPost" action="#" class="px-4 py-6 space-y-4">
<div class="overflow-hidden bg-white rounded-md shadow">
<div class="px-4 py-3 space-y-8 sm:p-6">
<div class="grid grid-cols-6 gap-6">
<div class="col-span-6 sm:col-span-3">
<input class="w-full" type="text"
wire:model="post.title" placeholder="Post title" />
</div>
</div>
<div class="flex flex-col">
<textarea id="body" rows="4" wire:model="post.body"
class="border-gray-300 rounded-sm form-textarea">
</textarea>
</div>
</div>
<div class="px-4 py-3 text-right bg-gray-50 sm:px-6">
<button type="submit" class="inline-flex justify-center">
post
</button>
</div>
</div>
</form>
</div>
</div>
this is my post create livewire method
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
use Illuminate\Http\Response;
class PostCreate extends Component
{
public $post;
public $points = 10;
public $energy = 1;
public function increment()
{
$this->points++;
}
protected $rules = [
// 'category' => 'required|integer|exists:categories,id',
'title' => 'required|min:4',
'body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$post = Post::create([
'user_id' => auth()->user()->id,
// 'category_id' => $this->category,
'body' => $this->body,
'title' => $this->title,
]);
$users = auth()->user();
$users->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('posts.index');
}
// abort(Response::HTTP_FORBIDDEN);
}
public function render()
{
return view('livewire.post-create');
}
}
There are two thing here to note - you don't initialize $this->post and you don't have the proper validation. You need to check for post.title and post.body, and you also need to display the actual errors.
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
class PostCreate extends Component
{
public $post;
public $points = 10;
public $energy = 1;
public function mount()
{
$this->post = new Post;
$this->post->user_id = auth()->id();
}
public function increment()
{
$this->points++;
}
protected $rules = [
// 'category' => 'required|integer|exists:categories,id',
'post.title' => 'required|min:4',
'post.body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$post = $this->post->save();
auth()
->user()
->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('posts.index');
}
// abort(Response::HTTP_FORBIDDEN);
}
public function render()
{
return view('livewire.post-create');
}
}
To display the errors from validation, you can add the following snippet in your blade-file,
#if ($errors->any())
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
Add lazy to the wire.model:
<input class="w-full" type="text" wire:model.lazy="post.title" placeholder="Post title" />
<textarea id="body" rows="4" wire:model.lazy="post.body" class="border-gray-300 rounded-sm form-textarea"></textarea>

Why livewire data binding is not working?

I have a livewire component and try to use it for CRUD operations. Most of the functionality works fine, but I can't load any record from the model in order to edit it. The form fields are empty when editing modal window pops up.
Snippet from component:
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Pais;
use Livewire\WithPagination;
class Paises extends Component
{
use WithPagination;
public $active;
public $q;
public $sortBy = 'id';
public $sortAsc = true;
public $pais;
public $confirmingPaisDeletion = false;
public $confirmingPaisAdd = false;
/* More code here but not relevant *********/
public function render()
{
$paises = Pais::select('id', 'pais','codiso2', 'codiso3', 'estatus')
->when( $this->q, function($query) {
return $query->where(function( $query) {
$query->where('pais', 'like', '%'.$this->q . '%')
->orWhere('codiso2', 'like', '%' . $this->q . '%')
->orWhere('codiso3', 'like', '%' . $this->q . '%');
});
})
->when($this->active, function( $query) {
return $query->active();
})
->orderBy($this->sortBy, $this->sortAsc ? 'ASC' : 'DESC');
$paises = $paises->paginate(10);
return view('livewire.paises', [
'paises' => $paises,
]);
}
public function updatingActive()
{
$this->resetPage();
}
public function updatingQ()
{
$this->resetPage();
}
public function sortBy( $field)
{
if( $field == $this->sortBy) {
$this->sortAsc = !$this->sortAsc;
}
$this->sortBy = $field;
}
public function confirmPaisDeletion( $id)
{
$this->confirmingPaisDeletion = $id;
}
public function deletePais( Pais $pais)
{
$pais->delete();
$this->confirmingPaisDeletion = false;
session()->flash('message', 'País eliminado correctamente');
}
public function confirmPaisAdd()
{
$this->reset(['pais']);
$this->confirmingPaisAdd = true;
}
public function confirmPaisEdit(Pais $pais)
{
$this->resetErrorBag();
$this->pais = $pais;
$this->confirmingPaisAdd = true;
}
/* More code here but not relevant */
Now the blade view.
Sinippet from record table generation code (with edit button):
<tbody>
#foreach($paises as $pais)
<tr>
<td class="border px-4 py-2">{{ $pais->id}}</td>
<td class="border px-4 py-2">{{ $pais->pais}}</td>
<td class="border px-4 py-2">{{ $pais->codiso2}}</td>
<td class="border px-4 py-2">{{ $pais->codiso3}}</td>
#if(!$active)
<td class="border px-4 py-2">{{ $pais->estatus ? 'Activo' : 'Inactivo'}}</td>
#endif
<td class="border px-4 py-2">
<x-jet-button wire:click="confirmPaisEdit( {{ $pais->id}})" class="bg-orange-500 hover:bg-orange-700">
{{ __('Editar') }}
</x-jet-button>
<x-jet-danger-button wire:click="confirmPaisDeletion( {{ $pais->id}})" wire:loading.attr="disabled">
{{ __('Borrar') }}
</x-jet-danger-button>
</td>
</tr>
#endforeach
</tbody>
Snippet from modal where we edit the record:
<x-jet-dialog-modal wire:model="confirmingPaisAdd">
<x-slot name="title">
{{ isset( $this->pais->id) ? 'Editar país' : 'Agregar país'}}
</x-slot>
<x-slot name="content">
<div class="col-span-6 sm:col-span-4">
<x-jet-label for="pais" value="{{ __('País') }}" />
<x-jet-input id="pais" type="text" class="mt-1 block w-full" wire:model.defer="pais.pais" />
<x-jet-input-error for="pais.pais" class="mt-2" />
</div>
<div class="col-span-6 sm:col-span-4 mt-4">
<x-jet-label for="codiso2" value="{{ __('Código ISO 2') }}" />
<x-jet-input id="codiso2" type="text" class="mt-1 block w-full" wire:model.defer="pais.codiso2" />
<x-jet-input-error for="pais.codiso2" class="mt-2" />
</div>
<div class="col-span-6 sm:col-span-4 mt-4">
<x-jet-label for="codiso3" value="{{ __('Código ISO 3') }}" />
<x-jet-input id="codiso3" type="text" class="mt-1 block w-full" wire:model.defer="pais.codiso3" />
<x-jet-input-error for="pais.codiso3" class="mt-2" />
</div>
<div class="col-span-6 sm:col-span-4 mt-4">
<label class="flex items-center">
<input type="checkbox" wire:model.defer="pais.estatus" class="form-checkbox" />
<span class="ml-2 text-sm text-gray-600">{{ __('Activo') }}</span>
</label>
</div>
</x-slot>
I just can't find where the problem is. Any suggestions?
as the Livewire documentation said, you must define rules for any model attribute to be edited:
public Pais $pais;
protected $rules = [
'pais.pais' => 'required',
'pais.codiso2' => 'required',
'pais.codiso3' => 'required',
'pais.estatus' => 'required'
];
//.....
public function confirmPaisEdit($id)
{
$this->resetErrorBag();
$this->pais = Pais::find($id);
$this->confirmingPaisAdd = true;
}
public function save()
{
$this->validate();
$this->pais->save();
}

Laravel - big collection and page load slow

I have a project for food ordering. On my object(restaurant) show page I'm calling all product categories with relationship for foreach products that belongs to that category.
I'm also using laravel livewire and this is my Component:
<?php
namespace App\Http\Livewire\Stores;
use Livewire\Component;
use Illuminate\Http\Request;
use App\Models\Store;
use App\Models\CategoryProduct;
use App\Models\Product;
use App\Http\Livewire\Cart;
use App\Models\Favourite;
use Session;
use Auth;
class Show extends Component
{
public $store;
public $categories;
public $ratings;
public $message = '';
public $supplements = [];
public $supplementsArray = [];
public $features = [];
public $featuresArray = '';
public $quantity = 1;
public $deliveryPrice = 0;
public function render(Request $request)
{
if(!Session::has('cart')){
return view('livewire.stores.show');
}
$items = explode('|', $this->featuresArray);
$oldCart = Session::get('cart');
$store_id = $this->store->id;
$oldCart->deliveryPrice = $this->store->delivery_price;
if($oldCart->storeId != $store_id){
$request->session()->forget('cart');
}
$cart = new Cart($oldCart);
//dd(session()->get('cart'));
return view('livewire.stores.show',[
'products' => $cart->items,
'totalPrice' => $cart->totalPrice + $cart->deliveryPrice,
'totalQty' => $cart->totalQty,
'ordersPrice' => $cart->ordersPrice,
'storeId' => $cart->storeId,
]);
}
}
This public $categories; variable is from my Controller:
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$store = Store::find($id);
$categories = CategoryProduct::where('store_id', $store->id)->get();
$ratings = $store->getAllRatings($store->id);
if($store->checkWorktime() == 'Zatvoreno'){
return view('website.stores.closed', compact('store', 'categories', 'ratings'));
}
return view('website.stores.show', compact('store', 'categories', 'ratings'));
}
And in my blade view this is how I'm viewing it:
#foreach($categories as $category)
<div class="row m-0" id="{{$category->id}}">
<h6 class="p-3 m-0 bg-light font-weight-bold w-100">{{$category->title}} <span class="float-right">
<small class="text-black-50">{{count($category->categoryProducts)}} proizvoda</small></span>
</h6>
<div class="col-md-12 px-0 border-top">
<div class="">
<ul class="list-group list-group-flush">
#foreach($category->categoryProducts as $product)
<a href="#0" class="list-group-item list-group-item-action" data-toggle="modal" data-target="#modal{{$product->id}}">
<div class="row">
<div class="col-9">
<b class="text-dark">{{$product->title}}</b><br>
<small class="text-muted">{{$product->description}}</small><br><br>
#if($product->features->isNotEmpty())
<small class="text-dark" style="font-size:14px !important;">od {{$product->price}}€</small>
#else
<small class="text-dark" style="font-size:14px !important;">{{$product->price}}€</small>
#endif
</div>
#if($product->thumbnail)
<div class="col-3">
<span class="float-right">
<img src="{{$product->thumbnail->getUrl('showPreview')}}" style="width:80px;height:80px;border-radius:50%;object-fit:cover;" alt="">
</span>
</div>
#endif
</div>
</a>
#include('website.stores.product-modal')
#endforeach
</ul>
</div>
</div>
</div>
#endforeach
And my page is loading crazy slow. I know I'm something doing wrong and I know that there is a way to speed this up. How can I do that?

Laravel - How to post data variables from 2 separate livewire component controllers, to a single blade file for CRUD functionality?

I wanted to post the variables initiated in the MenuItemList.php and SubCategoryList.php located in the App/Http/Livewire directory to a single blade file i.e. menu-item.blade.php. So I can further use the CRUD functionality for the above said tables i.e. menu-items and sub-categories from a single view, i.e. menu-item.blade.php.
When I run it through the different routes with separate views, it works flawlessly, but as soon as I try to combine them into one and try to view it all, in a single blade file, it gives me all sort of errors. Here is my source code.
App\Models\MenuItem.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class MenuItem extends Model
{
use HasFactory;
protected $table = "menu_items";
protected $fillable = ['sub_category_id', 'item_name', 'item_description'];
}
App\Http\Livewire\MenuItemList.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\MenuItem;
class MenuItemList extends Component
{
use WithPagination;
public $search;
public $itemId,$sub_category_id,$item_name,$item_description;
public $isOpen = 0;
public function render()
{
$searchParams = '%'.$this->search.'%';
return view('livewire.menu-item', [
'menuitemlist' => MenuItem::where('item_name','like', $searchParams)->latest()->paginate(5)
]);
}
public function showModal() {
$this->isOpen = true;
}
public function hideModal() {
$this->isOpen = false;
}
public function store(){
$this->validate(
[
'sub_category_id' => 'required',
'item_name' => 'required',
]
);
MenuItem::updateOrCreate(['id' => $this->itemId], [
'sub_category_id' => $this->sub_category_id,
'item_name' => $this->item_name,
'item_description' => $this->item_description
]);
$this->hideModal();
session()->flash('info', $this->itemId ? 'Post Update Successfully' : 'Post Created Successfully' );
$this->itemId = '';
$this->sub_category_id = '';
$this->item_name = '';
$this->item_description = '';
}
public function edit($id){
$menuitem = MenuItem::findOrFail($id);
$this->itemId = $id;
$this->sub_category_id = $menuitem->sub_category_id;
$this->item_name = $menuitem->item_name;
$this->item_description = $menuitem->item_description;
$this->showModal();
}
public function delete($id){
MenuItem::find($id)->delete();
session()->flash('delete','Post Successfully Deleted');
}
}
App\Models\SubCategory.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
use HasFactory;
protected $table = "sub_categories";
protected $fillable = ['category_id', 'sub_category_name'];
}
App\Http\Livewire\SubCategoryList.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\SubCategory;
class SubCategoryList extends Component
{
use WithPagination;
public $search;
public $itemId,$category_id,$sub_category_name;
public $isOpen = 0;
public function render()
{
$searchParams = '%'.$this->search.'%';
return view('livewire.sub-category', [
'subcategorylist' => SubCategory::where('sub_category_name','like', $searchParams)->latest()->paginate(5)
]);
}
public function showModal() {
$this->isOpen = true;
}
public function hideModal() {
$this->isOpen = false;
}
public function store(){
$this->validate(
[
'category_id' => 'required',
'sub_category_name' => 'required',
]
);
SubCategory::updateOrCreate(['id' => $this->itemId], [
'category_id' => $this->category_id,
'sub_category_name' => $this->sub_category_name
]);
$this->hideModal();
session()->flash('info', $this->itemId ? 'Post Update Successfully' : 'Post Created Successfully' );
$this->itemId = '';
$this->category_id = '';
$this->sub_category_name = '';
}
public function edit($id){
$subcategory = SubCategory::findOrFail($id);
$this->itemId = $id;
$this->category_id = $subcategory->category_id;
$this->sub_category_name = $subcategory->sub_category_name;
$this->showModal();
}
public function delete($id){
SubCategory::find($id)->delete();
session()->flash('delete','Post Successfully Deleted');
}
}
Routes\Web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Livewire\MenuItemList;
use App\Http\Livewire\SubCategoryList;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/menu-item', MenuItemlist::class);
Route::get('/sub-category', SubCategorylist::class);
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
EDITED
Here is my menu-item.blade.php for referencing, I am using the exact same code for the sub-category.blade.php, just using the variables from the SubCategory.php. As I am unable to show them in a single view, I have made two separate views for the above said files.
Resources\Views\Livewire\menu-item.blade.php
<x-slot name="header">
<h2 class="text-xl font-semibold leading-tight text-gray-800">
Manage Menu Item
</h2>
</x-slot>
<div class="py-12">
<div class="mx-auto max-w-5xl sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow sm:rounded-lg px-4 py-4 my-8 text-sm">
<div class="flex mb-4">
<div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
<button wire:click="showModal()" class="px-4 py-2 my-3 font-bold text-white bg-blue-500 rounded hover:bg-blue-700 focus:outline-none">Create Menu Item</button>
</div>
<div class="w-full md:w-1/2 px-3 mb-6 md:mb-0">
<input wire:model="search" type="text" class="shadow appearance-none border rounded w-full py-2 px-2 my-3 text-blue-900 focus:outline-none" placeholder="Search Post...">
</div>
</div>
#if($isOpen)
#include('livewire.create')
#endif
#if(session()->has('info'))
<div class="bg-green-500 border-2 border-green-600 rounded-b mb-2 py-3 px-3">
<div>
<h1 class="text-white font-bold">{{ session('info') }}</h1>
</div>
</div>
#endif
#if(session()->has('delete'))
<div class="bg-red-500 border-2 border-red-600 rounded-b mb-2 py-3 px-3">
<div>
<h1 class="text-white font-bold">{{ session('delete') }}</h1>
</div>
</div>
#endif
<table class="w-full table-fixed">
<thead>
<tr class="bg-gray-100">
<th class="w-20 px-4 py-2">Sr. No.</th>
<th class="px-4 py-2">Sub-Category ID</th>
<th class="px-4 py-2">Item Name</th>
<th class="px-4 py-2">Item Description</th>
<th class="px-4 py-2">Action</th>
</tr>
</thead>
<tbody>
#foreach($menuitemlist as $key=>$menuitem)
<tr style="background-color: {{ $key % 2 == 0 ? '#fdfdfd': '#f5f5f5' }};">
<td class="px-4 py-2">{{ $menuitemlist->firstitem() + $key }}</td>
<td class="px-4 py-2">{{ $menuitem->sub_category_id }}</td>
<td class="px-4 py-2">{{ $menuitem->item_name }}</td>
<td class="px-4 py-2">{{ $menuitem->item_description }}</td>
<td class="px-4 py-2">
<button wire:click="edit({{ $menuitem->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-4 rounded">
Edit
</button>
<button wire:click="delete({{ $menuitem->id }})" class="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-4 rounded">
Delete
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="mt-4">
{{$menuitemlist->links()}}
</div>
</div>
</div>
</div>

Missing required parameters for [Route: voluntier.submit.get] [URI: voluntier/submit/{id}]

I am currently working on my final project, but I got this error and I have tried to change the route action on my html to {{ route('voluntier.submit.get') }} but it still shows the error. Could anyone help me to find the solution.
Thank you so much
VoluntierController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Event;
use App\City;
use App\User;
use App\VoluntierProfile;
use App\Submission;
class VoluntierController extends Controller
{
public function index()
{
$data = Event::select('events.job_desk', 'events.location', 'events.city', 'events.job_description', 'events.fee', 'cities.name as city', 'job_desks.job_desk')
->leftJoin('job_desks', 'events.job_desk', 'job_desks.id')
->leftJoin('cities', 'events.city', 'cities.id')
->get();
$data_category_liaison = Event::select('events.job_desk')
->where('id' , '=', 2)
->count();
// dd($data_category);
return view('voluntier.index', compact('data', 'data_category_liaison'));
}
public function profile()
{
return view('voluntier.profile');
}
public function createProfile()
{
$city = City::all()->where('id', '!=', '0');
return view('voluntier.profile-edit', compact('city'));
}
public function storeProfile(Request $request)
{
$profile = new VoluntierProfile();
$profile->voluntier_id = $request->input('voluntier_id');
$profile->about = $request->input('tentang');
$profile->city_id = $request->input('kota');
$profile->address = $request->input('alamat');
$profile->latest_education = $request->input('pendidikan_terakhir');
$profile->save();
}
public function submitCreate($id)
{
$event = Event::find($id)->first();
$voluntier = Voluntier::find(Auth::user()->id)->get();
// dd($voluntier);
return view('voluntier.submit', compact('data'));
}
public function submitStore($id, Request $request)
{
$event = Event::find($id);
$voluntier = Auth::user();
$submission = new Submission();
$submission->event_id = $event->id;
$submission->voluntier_id = $voluntier->id;
$submission->status_id = $request->input('status');
$submission->save();
return redirect('voluntier/dashboard');
}
}
index.blade.php
#foreach($data as $row)
<td><a href="{{ route('voluntier.submit.get', $row->id) }}" class="job-item d-block d-md-flex align-items-center border-bottom fulltime">
<div class="company-logo blank-logo text-center text-md-left pl-3">
<img src="images/company_logo_blank.png" alt="Image" class="img-fluid mx-auto">
</div>
<div class="job-details h-100">
<div class="p-3 align-self-center">
<h3>{{ $row->job_desk }}</h3>
<div class="d-block d-lg-flex">
<div class="mr-3"><span class="icon-suitcase mr-1"></span>{{ $row->location }}</div>
<div class="mr-3"><span class="icon-room mr-1"></span>{{ $row->city }}</div>
<div><span class="icon-money mr-1"></span>Rp. {{ $row->fee }}</div>
</div>
</div>
</div>
<!-- <div class="job-category align-self-center">
<div class="p-3">
<span class="text-info p-2 rounded border border-info">Full Time</span>
</div>
</div> -->
</a></td>
#endforeach
submit.blade.php
<form action="{{ route('voluntier.submit.post', $event->id) }}" method="post" class="p-5 bg-white">
My route
web.php
Route::prefix('voluntier')->group(function() {
Route::get('/login', 'Auth\LoginController#showVoluntierLoginForm')->name('voluntier.login.get');
Route::post('/login/post', 'Auth\LoginController#voluntierLogin')->name('voluntier.login.post');
Route::get('/register', 'Auth\RegisterController#showVoluntierRegisterForm')->name('voluntier.register.get');
Route::post('/register/post', 'Auth\RegisterController#createVoluntier')->name('voluntier.register.post');
Route::get('/dashboard', 'VoluntierController#index')->middleware('auth:voluntier')->name('voluntier.dashboard');
Route::get('/profile', 'VoluntierController#profile')->middleware('auth:voluntier')->name('voluntier.get');
Route::get('/profile/get', 'VoluntierController#createProfile')->middleware('auth:voluntier')->name('voluntier.profile.get');
Route::post('/profile/post', 'VoluntierController#storeProfile')->name('voluntier.profile.post');
Route::get('/submit/{id}', 'VoluntierController#submitCreate')->middleware('auth:voluntier')->name('voluntier.submit.get');
Route::post('submit/post/{id}', 'VoluntierController#submitStore')->name('voluntier.submit.post');
});

Categories