Laravel - How to display child goal type name on select dropdown on edit form - laravel

In my Laravel-5.8 project, I am trying to child name (text) on select list in edit form.
I have this table:
CREATE TABLE `goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Model
class GoalType extends Model
{
public $timestamps = false;
protected $table = 'goal_types';
protected $primaryKey = 'id';
protected $fillable = [
'name',
'parent_id',
'max_score',
];
protected $casts = [];
public function children()
{
return $this->hasMany('App\Models\GoalType', 'parent_id');
}
public function parent()
{
return $this->hasOne(App\Models\GoalType::class, 'id', 'parent_id');
}
}
Controller
public function index()
{
$categories = GoalType::with('children')->whereNull('parent_id')->get();
return view('goal_types.index')->with('categories', $categories);
}
public function create()
{
return view('goal_types.create');
}
public function store(StoreGoalTypeRequest $request)
{
$data = GoalType::create([
'name' => $request->name,
'parent_id' => $request->parent_id,
'max_score' => $request->max_score,
]);
Session::flash('success', 'Goal Type is created successfully');
return redirect()->route('goal_types.index');
}
I have a modal form for the edit
view
<div class="row">
<div class="col-md-8">
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">Goal Type(s)</h3>
</div>
<div class="card-body">
<ul class="list-group">
#foreach ($categories as $category)
<li class="list-group-item">
#if ($category->children)
<ul class="list-group mt-2">
#foreach ($category->children as $child)
<li class="list-group-item">
<div class="d-flex justify-content-between">
{{ $child->name }}
<div class="button-group d-flex">
#can('goal_type_edit')
<button type="button" class="btn btn-sm btn-primary mr-1 edit-category" data-toggle="modal" data-target="#editCategoryModal" data-id="{{ $child->id }}" data-name="{{ $child->name }}">Edit</button>
#endcan
</div>
</div>
</li>
#endforeach
</ul>
#endif
</li>
#endforeach
</ul>
</div>
</div>
</div>
<div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Goal Type</h4>
<form action="" method="POST">
#csrf
#method('PUT')
<div class="modal-body">
<div class="form-group">
<label class="control-label"> Parent Goal Type:</label>
<select class="form-control select2bs4" data-placeholder="Choose Parent Goal Type" tabindex="1" name="parent_id" style="width: 100%;">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label"> Name:<span style="color:red;">*</span></label>
<input type="text" name="name" class="form-control" value="" placeholder="Category Name" required>
</div>
<div class="form-group">
<label class="control-label"> Max. Weight (%):</label>
<input type="number" name="max_score" class="form-control" value="" step="0.01" placeholder="Enter maximum weight here: 15, 50, 75 etc" style="width: 100%;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
When I click on edit from the index a modal form should popup to display the child name where the parent_id equals the id of the parent as it is in the database. But the select dropdown value/text is not displaying anything until when I click on the select dropdown.
How do I modify
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
in the edit to achieve that (displaying the name of the select child on the dropdown)?
Thanks

In your edit view you must pass your category id in your form action like this action="{{ route('admin.categories.update' , $category->id) }}" and then compare it with parent_id and in your category model you have to pass children.
category model:
public function children()
{
return $this->hasMany(GoalType::class, 'parent_id' , 'id')->with('children');
}
edit.blade.php view
<div class="col-md-12">
<label for="parent_id" class="form-control-label">parents category name</label>
<select class="form-control" data-toggle="select" data-live-search="true" name="parent_id" id="parent_id">
<option value="0" {{ $category->parent_id === 0 ? 'disabled' : '' }} selected> - Default</option>
#foreach(\App\Models\Category::latest()->get() as $cate)
<option value="{{ $cate->id }}" {{ $cate->id === $category->parent_id ? 'selected' : '' }} {{ $cate->id === $category->id ? 'disabled' : '' }} {{ $cate->id === $category->parent_id ? 'disabled' : '' }}>{{ $cate->name }}</option>
#endforeach
</select>
</div>

Related

How To Update hasMany relationship data with multiple row at a time in Laravel?

I want to update SubCategory, which has a relationship with Category as a hasMany relationship. Now I want to update both category and subcategory at a time from one form. I want to update every subcategory which belongs to the category. But I can't do that.
Here is category model:
class Category extends Model
{
use HasFactory;
protected $guarded=[];
public function subcategory(){
return $this->hasMany('App\Models\SubCategory');
}
Here is subcategory model:
class SubCategory extends Model
{
use HasFactory;
protected $guarded=[];
public function category(){
return
$this>belongsTo('App\Models\Category','category_id','id');
}
here is update function in controller:
public function categoryUpdate(Request $request,$id){
if (is_null($this->user) || !$this->user->can('categories-update')) {
abort(403, 'Sorry !! You are Unauthorized !');
}
$request->validate([
'name' => 'required|max:191',
'status' => 'required',
]);
$Category=Category::findOrFail($id);
$Category->name = $request->name;
$Category->slug = Str::slug($request->name);
$Category->status = $request->status;
$Category->updated_by=Auth::user()->id;
$Category->update();
if($request->subcategory_name !=['']){
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
SubCategory::create([
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
]);
}
}
}
Alert::success('Success','Category has been updated successfully!');
return redirect()->route('category.index');
}
I don't know the code to update multiple subcategories at a time.
Here is the Html form
<form action="{{ route('category.update', $data->id) }}" method="POST">
#csrf
<div class="form-group">
<label for="" class="mb-2">Category name</label>
<input name="name" class="form-control" value="{{ $data->name }}" type="text"
#error('name') is-invalid #enderror" placeholder="Name">
#error('name')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div><br>
<div class="form-group">
<label for="" class="mb-2">SubCategory name</label>
#foreach ($subcat as $sub)
<div class="d-flex w-70 justify-content between mb-2">
<input name="subcategoryname[]" id="subcategoryname" class="form-control w-50" type="text" value="{{json_decode($sub->name)}}"></input>
<button onclick="deleteSubcategory({{$sub->id}})" id="delete_subcat" class="btn btn-danger btn-sm ms-2"><i
class="fa fa-trash text-dark" style="font-size:20px;color:white!important"
aria-hidden="true"></i></button>
</div>
#endforeach
</div><br>
<div class="form-group mt-2">
<label for="" class="mb-2">Add New SubCategory</label>
<div class="subcategory w-50">
<div class="d-flex mb-2">
<input name="subcategory_name[]" class="form-control" id="name" type="text"
placeholder="Name" multiple>
<span id="add" class="btn btn-dark ms-3">+</span>
</div>
</div>
<div class="form-group mt-2">
<label for="" class="mb-2">Status</label>
<br>
<select name="status" class="form-control" style="width:40%"
#error('status') is-invalid #enderror">
<option value="">--Select Status--</option>
<option value="Active" #if ($data->status == 'Active') selected #endif>Active
</option>
<option value="Inactive" #if ($data->status == 'Inactive') selected #endif>Inactive
</option>
</select>
#error('status')
<div class="text-danger">* {{ $message }}</div>
#enderror
</div>
<div class="form-group mt-4 d-flex justify-content-between">
<button type="button" class="btn btn-secondary btn-sm"
data-bs-dismiss="modal">Cancel</button>
<input class="btn btn-primary btn-sm"type="submit" value="Update">
</div>
</form>
The create method takes array of records you want to save. So you can build an array and pass that array to the create method on the SubCategory.
if($request->subcategory_name !=['']){
$subCategories = [];
foreach($request->subcategory_name as $subcat){
if($subcat !=''){
$subCategories[] = [
'name'=>json_encode($subcat),
'slug'=>Str::slug(json_encode($subcat)),
'category_id'=>$id,
'created_by' =>Auth::user()->id,
];
}
}
SubCategory::updateOrCreate(['name', 'slug'], $subCategories);
}

Error store data laravel when have image in pages

I am insert data product with images in dashboard, when I try to order the product I have error 404 not found and the URL showing value database in table like http://127.0.0.1:8000/shops/order/[%7B%22id%22:2,%22category_id%22:1,%22name_product%22:%22asdasd%22,%22harga%22:123123123,%22image%22:%22product-images//HapOzHmJPim1kIfmIeCM21xesCnIbR5Z7lpzcO8M.jpg%22,%22published_at%22:null,%22created_at%22:%222022-05-23T16:25:00.000000Z%22,%22updated_at%22:%222022-05-23T16:25:10.000000Z%22,%22kategori%22:%7B%22id%22:1,%22name_category%22:%22Top%22,%22created_at%22:%222022-05-23T16:22:40.000000Z%22,%22updated_at%22:%222022-05-23T16:22:40.000000Z%22%7D%7D].
But when I am insert data product without images in dashboard, and then I try to order the product is successful.
This is my route
Route::post('/shops/order/{shop:id}', [OrderController::class, 'store']);
This is OrderController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\User;
use App\Models\Shop;
class OrderController extends Controller
{
public function store(Request $request)
{
$createOrder = $request->validate([
'user_id' => 'required',
'name_product_id' => 'required',
'size' => 'required',
'no' => 'required',
'address' => 'required'
]);
Order::create($createOrder);
return redirect('shops/order/{shop:id}')->with('success', 'Order is successfully!');
}
}
This is my views
#extends('layouts.main')
#section('container')
<div class="container">
<div class="row mt-5">
#foreach ($shops as $shop)
<div class="card mb-3">
<div class="row g-0">
<div class="col-md-4">
<img src="{{ asset('storage/' . $shop->image) }}" alt="{{ $shop->name_product }}" class="img-fluid rounded-start" style="max-height: 400px; overflow:hidden">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{{ $shop->name_product }}</h5>
<p>Jenis {{ $shop->category->name_category }}</p>
<p class="card-text fw-bold">Rp.{{ $shop->price }}</p>
</div>
</div>
</div>
</div>
#endforeach
</div>
<div class="row mt-5">
<div class="col align-self-center">
#if (session()->has('success'))
<div class="alert alert-success text-center" role="alert">
{{ session('success') }}
</div>
#endif
</div>
</div>
<form method="POST" action="/shops/order/{{ $shops }}" class="row g-2" enctype="multipart/form-data">
#csrf
<h3 class="text-center mt-2">Detail Delivery</h3>
<div class="col-md-6">
<div class="mb-3">
<select class="form-select" name="user_id" hidden>
#foreach ($users as $name)
<option value="{{ $name->id }}">{{ $name->id }}</option>
#endforeach
</select>
</div>
<div class="mb-3">
<select class="form-select" name="name_produk_id" hidden>
#foreach ($shops as $shops_id)
<option value="{{ $shops_id->id }}">{{ $shops_id->id }}</option>
#endforeach
</select>
</div>
<div class="mb-3">
<label for="address" class="form-label">Address</label>
<textarea class="form-control" #error('address') is-invalid #enderror id="address" name="address" required>
</textarea>
</div>
</div>
<div class="col-md-4">
<label for="size" class="form-label mt-3">Select size :</label>
<select class="form-select" name="size">
<option selected>S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<div class="mt-3">
<label for="no" class="form-label">Nomor Whatsapp</label>
<input class="form-control" #error('no') is-invalid #enderror id="no" name="no" required autofocus">
</div>
<button type="submit" class="btn btn-primary mt-5">Buy Now</button>
</div>
</form>
</div>
#endsection

How to insert this array of mySbjects in a database?

I've been trying to insert this into the database and I don't have any idea how to store this information into the database... The relationship between user and grade is many-to-many and between grade and mySubject is One-to-many.
<div class="row">
#foreach($grades as $grade)
<div class="card shadow mx-2 my-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold">
<div class="custom-control custom-checkbox">
<input class="custom-control-input #error('grade') is-invalid #enderror" type="checkbox" id="{{$grade->id}}" name="grade[]" value="{{ $grade->id }}"/>
<label class="custom-control-label pt-1" for="{{$grade->id}}">{{$grade->name}}</label>
</div>
</h6>
</div>
<div class="card-body">
#foreach($grade->subjects as $subject)
<div class="custom-control custom-checkbox mb-2">
<input class="custom-control-input" type="checkbox" id="{{$grade->id}}{{$subject->id}}" name="mySubjects[{{$grade->id}}][]" value="{{ $subject->name }}"/>
<label class="custom-control-label" for="{{$grade->id}}{{$subject->id}}">
{{$subject->name}}
</label>
</div>
#endforeach
</div>
</div>
#endforeach
</div>
The store function
public function store(Request $request)
{
$user->grades()->sync($request->grade);
if($request->mySubjects){
//. . . .
}
}
}
Try below code:
public function store(Request $request)
{
$user->grades()->sync($request->grade);
if($request->mySubjects){
$mySubjects = $request-> mySubjects;
$data = [];
foreach($mySubjects as $subject){
array_push($data,
'your database field name'=> $subject,
'created_at' => now()->toDateTimeString(),
'updated_at' => now()->toDateTimeString(),
}
YourModelName::insert($data);
}
}
}

Laravel Error during update - Undefined variable: id

I am working on a project using Laravel-5.8
protected $table = 'ratings';
protected $fillable = [
'rating_type',
'rating_value',
'rating_description',
];
public function rules()
{
return [
'rating_type' => 'required|numeric|min:1|max:10|unique:appraisal_ratings,rating_type,company_id'.$this->id,
];
}
The rating has an id column, and that's the primary key. Why I checked it against company_id is that different companies can have the same rating type.
Controller
public function edit($id)
{
$rating = Rating::where('id', $id)->first();
return view('ratings.edit')
->with('rating', $rating)
->with('rating_types', $this->rating_types)
->with('rating_descriptions', $this->rating_descriptions)
->with('rating_values', $this->rating_values);
}
public function update(UpdateRatingRequest $request, $id)
{
$rating = Rating::find($id);
$rating->rating_type = $request->rating_type;
$rating->rating_value = $request->rating_value;
$rating->rating_description = $request->rating_description;
$rating->save();
Session::flash('success', 'Rating is updated successfully');
return redirect()->route('ratings.index');
}
edit.blade
<form action="{{route('ratings.update', ['id'=>$rating->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="rating_type" style="width: 100%;">
<option value="">Select Rating</option>
#foreach($rating_types as $k => $rating_type)
<option value="{{$k}}" #if($rating->rating_type == $k) selected #endif>{{$rating_type}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Description:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Description" tabindex="1" name="rating_description" style="width: 100%;">
<option value="">Select Description</option>
#foreach($rating_descriptions as $k => $rating_description)
<option value="{{$k}}" #if($rating->rating_description == $k) selected #endif>{{$rating_description}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating Score:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating Score" tabindex="1" name="rating_value" style="width: 100%;">
<option value="">Select Rating Score</option>
#foreach($rating_values as $k => $rating_value)
<option value="{{$k}}" #if($rating->rating_value == $k) selected #endif>{{$rating_value}}</option>
#endforeach
</select>
</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('ratings.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
When I clicked on the save button to update, I got this error:
rating_type already exists.
That error should not have occured since I am doing update.
How do I resolve it?
Thank you.
You are checking the unique on update wrong
Unique Rule Usage
unique:table,column,except,idColumn
* 3rd param is for value for column to except and 4th is for column to except
Fix
//App\Http\Requests\UpdateRatingRequest
'rating_type' => 'required|numeric|min:1|max:10|unique:table_name,rating_type,table_primary_key'.$this->id,

when click submit error is occur

when click on submit data,data successfully save and show in database but got error in index page, i think don't get it user-id
Trying to get property 'id' of non-object (View:
C:\xampp\htdocs\ytl\resources\views\profile\index.blade.php)
This is index.blade.php file
<form method="post", id="form", action="{{action('Profile\UserProfileController#index')}}" accept-charset="UTF-8">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6 mb-3 form-group">
Exchange:<select name="exchange_id" id="exchange" class="form-control " onchange="myfunc()">
<option value="">Select</option>
#foreach($exchanges as $key=>$val )
<option value="{{ $val->id }}">{{ $val->exchange }}</option>
#endforeach
</select>
{{--{!! Form::label('exchange_id', 'Exchanges: ') !!}--}}
{{--{!! Form::select('exchange_id', ['' => 'Choose Options'] + $exchanges, null, ['class' => 'form-control', 'id' => 'exchange', 'name' => 'exchange_id'])!!}--}}
</div>
<div class="col-md-6 mb-3 form-group">
Market<select name="market_id" id="market" class="form-control bindselect" >
<option value="">Select</option>
{{--#foreach($markets as $key=>$val )--}}
{{--<option value="{{ $val->id }}">{{ $val->market }}</option>--}}
{{--#endforeach--}}
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Country:<select name="country_id" id="country" class="form-control " >
<option value="">Select</option>
#foreach($countries as $key=>$val )
<option value="{{ $val->id }}">{{ $val->country }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Company:<select name="brokerage_company_id" id="brokerage_company_id" class="form-control " >
<option value="">Select</option>
#foreach($brokerage_company as $key=>$val )
<option value="{{ $val->id }}">{{ $val->brokerage_company }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
{{--{!! Form::label('Intraday_Charge', 'Intraday Charge:') !!}--}}
{{--{!! Form::text('Intraday_Charge', null, ['required' => 'required', 'class'=>'form-control number_only'])!!}--}}
Intraday_charge: <input type="text" name="charge_intraday" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_delivery" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_lot" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_order" class="form-control"><br>
</div>
<div class="mb-3 form-group">
{{--{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}--}}
<input type="submit" value="Submit">
</div>
</div>
</form>
This is controller in which 2 method. 1st index and 2nd store method
public function index(Request $request){
$exchanges = Exchange::select('exchange','id')->get();
$markets = Market::select('market','id')->get();
$countries = Country::select('country','id')->get();
$brokerage_company = BrokerageCompany::select('brokerage_company','id')->get();
return view('profile.index', compact( 'exchanges','markets','countries','brokerage_company'));
}
public function store(Request $request){
$Input = $request->all();
$user = Auth::user();
$user->userprofile()->create($Input);
$user_id = Auth::user()->id;
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$countries = Country::pluck('country','id')->all();
$brokerage = BrokerageCompany::pluck('brokerage_company','id')->all();
$user_profile = UserProfile::pluck('charge_intraday','charge_delivery','charge_per_lot','charge_per_order');
return view('profile.index', compact( 'exchanges','markets','countries','brokerage','user_profile'));
}
Since Laravel 5.2 pluck() method of Eloquent builder returns a collection of values from given column. When you call all() on this collection, you simply get an array of values from that first column. For example, when you call
$exchanges = Exchange::pluck('exchange','id')->all();
$exchanges will be an array that contains all values of exchange column in your Exchanges table. Hence the error, as you're trying to access id attribute of this scalar value.
I guess you're trying to limit number of columns fetched from the database. Call select() method instead of pluck():
$exchanges = Exchange::select('exchange','id')->get();

Resources