my livewire app is returning 404 not found when I selected a dropdown item - laravel

I am designing a laravel app, which I used module and livewire. I have a dropdown item which when I selected an item its returned an error 404 NOT FOUND
Here is my livewire component.
I am thinking may the wire:model="selectedSession" and wire:model="selectedTerm" is having problem
please i need your help
<?php
namespace Modules\Student\Http\Livewire;
use Livewire\Component;
use Modules\Student\Entities\Result;
use Modules\Student\Entities\Term;
use Modules\Student\Entities\Section;
class ResultDependance extends Component
{
public $selectedSession = null;
public $selectedTerm = null;
public $results;
public function mount($id)
{
$this->results = Result::with('student', 'section', 'term', 'subject')->where('student_id', $id)->get();
}
public function render()
{
return view('student::livewire.pages.resultdependance',
['terms' => Term::all()],
['sessions' => Section::all()]
);
}
}
my blade.php codes
<div class="section">
<div class="card">
<div class="card-body">
<div class="card-title">
<h4><strong>Result</strong></h4>
<div class="form">
<form action="" method="post">
{{csrf_field()}}
<div class="form-group">
<select name="session" id="" class="form-control form-select" wire:model="selectedSession">
<option selected>Select Session</option>
#foreach($sessions as $session)
<option value="{{$session->id}}">{{$session->section_title}}</option>
#endforeach
</select>
</div>
<br>
<div class="form-group">
<select name="term" id="" class="form-control form-select" wire:model="selectedTerm">
<option selected>Select Term</option>
#foreach($terms as $term)
<option value="{{$term->id}}">{{$term->term}}</option>
#endforeach
</select>
</div>
<input type="button" value="test" wire::loading.attr='disabled'>
<h1 wire:loading>please wait</h1>
</form>
<br>
</div>
</div>
</div>
</div>
</div>
I am designing a laravel app, which I used module and livewire. I have a dropdown item which when I selected an item its returned an error 404 NOT FOUND
Here is my livewire component.
I am thinking may the wire:model="selectedSession" and wire:model="selectedTerm" is having problem
please i need your help

It's missing the logic to filter the results based on the selected session and term.
you can do it by using livewire hooks or by adding this
public function filterResults()
{
$this->results = Result::with('student', 'section', 'term', 'subject')->where('student_id', $id)->where('section_id', $this->selectedSession)->where('term_id', $this->selectedTerm)->get();
}
and in your selectedSession
<select name="session" id="" class="form-control form-select" wire:model.lazy="selectedSession" wire:change="filterResults">
Now when the user changes the selected session or term, the component will filter the results and update the view accordingly.

Related

Laravel Livewire : livewire multiple root elements detected

I'm currently developing a website using laravel livewire
The website has a multi-site form page, and there's a dynamic dropdown on the inside of that multi-site form page
The problem is when the form is filled, it won't store the data into the database
When i do inspect the website there's an error that read :livewire multiple root elements detected
How do i fix this??
Livewire model :
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Kredit;
use App\Models\Biaya;
use App\Models\Produk;
use App\Models\Promo;
use App\Models\Motorcycle;
use App\Models\MotorcycleBrand;
use App\Models\Domisili;
class KreditMulti extends Component
{
public $brand_id;
public function render()
{
$domisilis = Domisili::all();
// $motorcycles = Motorcycle::all();
// $motorcycle_brands = MotorcycleBrand::all();
//for the dynamic dropdown
if($this->brand_id){
$motorcycle_brands = MotorcycleBrand::where('motorcycle_id', $this->brand_id)->get();
} else {
$motorcycle_brands = [];
}
return view('livewire.kredit-multi',
['domisilis'=>$domisilis])
->withMotorcycles(Motorcycle::all())
->with('motorcycle_brands', $motorcycle_brands);
}
}
The livewire blade php :
<div class="form-group row">
<label for="motorcycle" class="col-md-4">Merek motor</label>
<div class="col-md-6">
<select wire:model="brand_id" class="form-control">
<option value="" selected>Choose Motor</option>
#foreach ($motorcycles as $m)
<option value="{{$m->id}}">{{$m->motorcycle_name}}</option>
#endforeach
</select>
</div>
</div>
<br>
#if (count($motorcycle_brands) > 0)
<div class="form-group row">
<label for="motorcycle_brand" class="col-md-4 col-form-label text-md-right">Jenis Motor</label>
<div class="col-md-6">
<select class="form-control" name="motorcycle_brand_id">
<option value="" selected>Choose the motor version</option>
#foreach ($motorcycle_brands as $motor)
<option value="{{$motor->id}}" wire:key="motorcycle_brand{{$motor->id}}">{{$motor->motorcycle_brand_name}}</option>
#endforeach
</select>
</div>
</div>
#endif
<br>
all livewire components must be start with a <div> and end with a </div>.
actually you must wrap the whole <div> and </div> s into a single <div></div>
Your blade code has several roots
1.- <div class="form-group row"....>
2.- <br>
3.- #if (count($motorcycle_brands) > 0)...#endif
4.- <br>
Enclose all that stuff in a single root
<div>
<div class="form-group row"....>
<br>
#if (count($motorcycle_brands) > 0)...#endif
<br>
</div>
The error is as exact as it can be. A Livewire component simply can only have a single root element. Instead, you're adding 2, including 2 breaks.
Wrap the whole component into a single <div></div>, and then it should be fixed.
public $motorcycle_brands,$domisilis,$brand_id,$motorcycles;
public function render()
{
$this->domisilis = Domisili::all();
$this->motorcycles = Motorcycle::all();
if($this->brand_id){
$this->motorcycle_brands = MotorcycleBrand::where('motorcycle_id', $this->brand_id)->get();
} else {
$this->motorcycle_brands = [];
}
return view('livewire.kredit-multi');
}
Blade
#if (count($motorcycle_brands) > 0)
<div class="form-group row">
<label for="motorcycle_brand" class="col-md-4 col-form-label text-md-right">Jenis Motor</label>
<div class="col-md-6">
<select class="form-control" wire:model="brand_id">
<option value="" selected>Choose the motor version</option>
#foreach ($motorcycle_brands as $motor)
<option value="{{$motor->id}}">{{$motor->motorcycle_brand_name}}</option>
#endforeach
</select>
</div>
</div>
#endif

Livewire magic actions not working Uncaught ReferenceError: $event is not defined

<div class="row">
<div class="col">
<div class="container">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<div class="mb-5">
<label class="form-label">Order: </label>
<select wire:change="selectOrder($event.target.value)">
#foreach($orders as $option)
<option value="{{$option['id']}}">{{$option['id']}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
public function selectOrder($order)
{
$this->order = $order;
$this->products = $this->order->products;
}
here is a live wire component that has a select input I need when changing the select the function selectOrder is executed with the selected value, i use $event magic action but i got the following error.
The $event is the Alpine.js magic property.
So one way to solve it is to have use an Alpine.js event listener, that calls the Livewire method.
<select x-on:change="$wire.selectOrder($event.target.value)">
That said, you could use a property in the Livewire class, and bind the select to a model,
<select wire:model="orderValue">
And then in the component listen for that change.
public $orderValue;
// ...
public function updated($field, $value)
{
if ($field === 'orderValue') {
$this->selectOrder($value);
}
}

pass user request in form action route in laravel 8

here is my simple form
<form id="test-form" class="white-popup-block mfp-hide">
<div class="popup_box ">
<div class="popup_inner">
<h3>Make an Appointment</h3>
<form action="{{route('doctorwithdatepopup',['date'=>$date,'id'=>$doctorsid])}}" method="POST">
#csrf
<div class="row">
<div class="col-xl-6">
<input id="datepicker" placeholder="Pick date" name="date">
</div>
#php
$Department = DB::table('departments')->orderBy('id','desc')->get();
#endphp
<div class="col-xl-6">
<select class="form-select wide" id="departmentid" name="departmentid">
<option data-display="Select Department">Department</option>
#foreach ($Department as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select>
</div>
<div class="col-xl-12">
<select class="form-select wide" id="doctorsid" name="doctorsid" class="">
</select>
</div>
<br>
<br>
<div class="col-xl-12">
<button type="submit" class="boxed-btn3">Search</button>
</div>
</div>
</form>
</div>
</div>
</form>
inaction ['date'=>$date,'id'=>$doctorsid] these two data I want pass based on user selection how can I do that?
for example
$date = $request->date
this one can handle in the controller but in action URL how can I pass user enter values ?
Little tricky. Try to make 2 routes for that, first route to get user form requests. Second, your "doctorwithdatepopup" routes.
web.php
Route::post('url', [YourController::class, 'store'])->name('storeform');
Route::get('url2/{date}/{id}', [YourController::class, 'show'])->name('doctorwithdatepopup');
YourController.php
public function store(Request $request)
{
// Some Validation, Logic, etc
return redirect()->route('doctorwithdatepopup', ['date' => $request->date, 'id' => $doctorId]);
}
public function show($date, $id)
{
return view('your view', compact('date', 'id'));
}

Laravel - Validate textinput value with database value

I am using Laravel-5.8 for a web application. In the project I want the users to set goals using these two tables:
class GoalType extends Model
{
protected $table = 'goal_types';
protected $fillable = [
'name',
'parent_id',
'is_current',
'max_score',
];
public function children()
{
return $this->hasMany('App\Models\GoalType', 'parent_id');
}
public function goals()
{
return $this->hasMany('App\Models\Goal');
}
}
class Goal extends Model
{
protected $table = 'appraisal_goals';
protected $fillable = [
'goal_type_id',
'employee_id',
'weighted_score',
'goal_description',
'goal_title',
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
As shown in the diagram below, GoalType is an hierarchical table. Only the parent have the max_score:
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('goals.create')
->with('categories', $categories);
}
public function store(StoreGoalRequest $request)
{
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->save();
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
create.blade
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('goals.store')}}">
#csrf
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Weight:</label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
From the diagram above, GoalType (goal_type_id) dropdown contains all the children fields from goal_types. What I want to achieve is this:
When Goal Type is selected from the dropdown, the system goes to the goals table (Goal). It displays total weighted_score based on employee_id and goal_type_id.
When the user tries to enter data into weight text field (weighted_score), the application adds the value in the text field to the result in number one (1) above. If the result is more than the max_score in goal_types (GoalType) based on the parent max_score, then an error message is displayed.
How do I achieve this?
Thank you.
You have to use AJAX for this, if you're unfamiliar with it, you can read about it here: https://www.w3schools.com/xml/ajax_intro.asp
I would also use JQuery to make things simpler. This way, you can do like this:
When Goal Type is selected from the dropdown, the system goes to the goals table (Goal). It displays total weighted_score based on employee_id and goal_type_id.
here you have to send to backend the goal type the user selected, for that, set an on change event in the combobox that triggers the AJAX request:
$('#goal_type').change(request_goals($('#goal_type').val()))
And the request_goals function should be like this:
function request_goals(){
$.ajax({
method: "GET",
dataType: 'json',
url: /*YOUR CONTROLLER URL*/,
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log("error");
},
success: function (response) {
/* HERE DO WHAT YOU NEED */
}
}
You will have to create a route and a controller function that returns the data you need.
When the user tries to enter data into weight text field (weighted_score), the application adds the value in the text field to the result in number one (1) above. If the result is more than the max_score in goal_types (GoalType) based on the parent max_score, then an error message is displayed.
Here you should do the same trick, set an event handler in the weighted_score field that sends an ajax request.
I hope it can help you.
If you want to archive it without AJAX calls, you can submit the form on select box change: <select name="goal_type_id" onchange="this.form.submit()">
In the controller you can catch the old input with old("goal_type_id"). You can query/calculate now the total weighted_score.

How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.
I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser
enter image description here
When I click edit button browser can show like that below image to perform edit operation
enter image description here
where brand name & image can't shown edit product form
My productController code below like that
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
use App\Product;
use Illuminate\Support\Facades\DB;
class productController extends Controller
{
public function index(){
$product = DB::table('products')
->join('brands','products.brandID','=','brands.brandID')
-> select('products.*','brands.brandName')
->get();
return view('admin.product.productList',compact('product'));
}
public function create()
{
$product = brand::pluck('brandName','brandID');
return view('admin.product.createProduct',compact('product'));
}
public function store(Request $request)
{
// image upload
$product = $request->except('image');
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$product['image'] = $imageName;
}
Product::create($product);
return view('admin.product.productList', compact('product'));
}
public function show($id)
{
$product = Product::find($id);
return view('admin.product.editProduct',compact('product'));
}
public function edit($id)
{
}
public function delete($id){
$product= Product::find($id);
$data=$product->delete();
return view('admin.product.productList',compact('data'));
}
}
my editProduct.blade file code below like that
#extends('layouts.master')
#section('content')
<div class="container" align="center">
<div class="col-md-6 col-md-offset-3">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Edit Product
</div>
<div class="panel-body">
<form action="edit" class="form-horizontal" method="POST>
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand :</label>
<div class="col-md-6">
<select name=" " class="form-control" >
<option>
</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description:</label>
<div class="col-md-6">
<input id="description" class="form-control" name="description" value="{!! $product->description !!}" required>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price:</label>
<div class="col-md-6">
<input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
</div>
</div>
<div class="form-group">
<label for="image" class="col-md-4 control-label">Image:</label>
<div class="col-md-6">
<input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
ADD
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.
So how can I show brand name & image to edit in the editProduct blade file. Pls help me
There are couple of ways, here's 1 way.
In your controller.
public function edit($id)
{
$product = Product::find($id);
$data = [
'product_info' => $product
];
return view('your.edit.view.here', $data);
}
And inside your view, inside the FORM Tag, do the looping.
#foreach($product_info as $info)
// data info here
<input id="description" value="{{ $product->description }}" required>
#endforeach
EDIT::
Use Laravel Encryption, you need it especially web apps like shopping cart.
URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
$id = decrypt($id);
}

Resources