while using Edit function in controller missing parameter error is showing up and when checked using dd {#connection: null #table: null } - laravel-8

i am trying to make a edit function for my subcategories while its show eerror like missing parament, dd showing connection null
the web.php in my routes
web.php
<?php
use App\Http\Controllers\SubCategoryController;
Route::resource('/subcategory', SubCategoryController::class);
the subcategorycontroller
controller
public function edit(subCategory $subCategory)
{
// dd($subCategory);
}
the subcategory model
model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
use HasFactory;
protected $fillable =['name'];
}
my migration file for subcategory
migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSubCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('sub_categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('category_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('sub_categories');
}
}
the output for dd
output
App\Models\SubCategory {#1377 ▼
#fillable: array:1 [▶]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: []
#original: []
#changes: []
#casts: []
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
the connection and table is showing null when its supposed to say mysql,subcategory
i am also providing the code where i did not used dd and done normaly and its error
controller
public function edit(subCategory $subCategories)
{
// dd($subCategories);
return view('subcategory/edit', compact('subCategories'));
}
the edit.blade.php file in my views
edit.blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">Edit Category</div>
<div class="card-body">
<form method="POST" action="{{ route('subcategory.update',[$subCategories->id]) }}">
#method('PUT')
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" required autocomplete="name" autofocus>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Commit Changes') }}
</button>
<a class="btn btn-primary" href="{{route('subcategory.index')}}">{{ __('lang.Cancel') }}</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and the output of missing parameter was obtained
output
Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: subcategory.update] [URI:
subcategory/{subcategory}] [Missing parameter: subcategory]. (View:
C:\xampp\htdocs\Exam\resources\views\subcategory\edit.blade.php)
http://127.0.0.1:8000/subcategory/1/edit
how can i solve this

changing the edit function in the controller fixed the problem
public function edit($id)
{
$subCategory = Subcategory::find($id);
return view('subcategory/edit', compact('subCategory'));
}

Related

Laravel 8 - Login Authentication Failed

Im new to Laravel and i have an error when i tried to login into my user, I have tried to identify the mistake and i think it would be in the auth()->attempt in SessionsController.php.
I tried to ddd($attributes); before the auth()->attempt and the input is there but it failed in auth()->attempt. So i tried ddd(auth()->attempt) and i got false.
If anyone know how to fix this please help me :(
This is my error
Below is my code:
routes/web.php:
Route::get('login', [SessionsController::class, 'create'])->middleware('guest');
Route::post('login', [SessionsController::class, 'store'])->middleware('guest');
sessions.create.blade.php (Login Page)
<form method="POST" action="/login" class="mt-10">
#csrf
<!-- Email -->
<div class="mb-6">
<label for="email" class="block mb2 uppercase font-bold text-xs text-gray-700">
Email
</label>
<input type="email" class="border border-gray-400 p-2 w-full" name="email" id="email" value="{{ old('email') }}" required>
#error('email')
<p class="text-red-500 text-xs mt-1">{{ $message }}</p>
#enderror
</div>
<!-- Password -->
<div class="mb-6">
<label for="password" class="block mb2 uppercase font-bold text-xs text-gray-700">
Password
</label>
<input type="password" class="border border-gray-400 p-2 w-full" name="password" id="password" required>
#error('password')
<p class="text-red-500 text-xs mt-1">{{ $message }}</p>
#enderror
</div>
<!-- Submit -->
<div class="mb-6">
<button type="submit" class="bg-blue-400 text-white rounded py-2 px-4 hover:bg-blue-500">
Log In
</button>
</div>
</form>
create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $guarded = [];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt('$password');
}
public function posts()
{
return $this->hasMany(Post::class);
}
}
SessionsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades;
class SessionsController extends Controller
{
public function create()
{
return view('sessions.create');
}
public function store()
{
$attributes = request()->validate([
'email' => 'required|email',
'password' => 'required',
]);
// ddd($attributes);
///ddd(auth()->attempt($attributes));
if (auth()->attempt($attributes)) {
return redirect('/')->with('success', 'Welcome Back!');
}
throw ValidationException::withMessages(['email' => 'Your provided credentials could not be verified.']);
}
public function destroy()
{
auth()->logout();
return redirect('/')->with('success','Goodbye!');
}
}

Add to cart button doesn't work. After click the button cart page doesn't load

This is Laravel 8.I set '/cart' route to href of add to cart button.but it also didn't work.got an error as 'session not found'.I made this while watching a youtube video.But it's not work.
What is the problem of my code?
Plz help me!
ShopComponent.php
<?php
namespace App\Http\Livewire;
use App\Models\Product;
use Livewire\Component;
use Livewire\WithPagination;
use Cart;
class ShopComponent extends Component
{
public function store($product_id,$product_name,$product_price){
Cart::add($product_id,$product_name,1,$product_price)->asseociate('App\Models\Product');
session()->flash('success_message','Item added in Cart');
return redirect()->route('product.cart');
}
public function render()
{
$products = Product::paginate(12);
return view('livewire.shop-component',['products'=>$products])->layout("layouts.base");
}
}
shop-component.blade.php
<div class="product-info">
<span>{{$product->name}}</span>
<div class="wrap-price"><span class="product-price">{{$product->regular_price}}</span></div>
Add To Cart
</div>
web.php
<?php
use App\Http\Livewire\HomeComponent;
use App\Http\Livewire\ShopComponent;
use App\Http\Livewire\CartComponent;
use App\Http\Livewire\CheckoutComponent;
use App\Http\Livewire\DetailsComponent;
use App\Http\Livewire\User\UserDashboardComponent;
use App\Http\Livewire\Admin\AdminDashboardComponent;
use Illuminate\Support\Facades\Route;
Route::get('/cart',CartComponent::class)->name('product.cart');
app.php
'aliases' => Facade::defaultAliases()->merge([
// 'ExampleClass' => App\Example\ExampleClass::class,
])->toArray(),
DetailsComponent.php
<?php
namespace App\Http\Livewire;
use App\Models\Product;
use Livewire\Component;
use Cart;
class DetailsComponent extends Component
{
public $slug;
public function mount($slug){
$this->slug=$slug;
}
public function store($product_id,$product_name,$product_price){
Cart::add($product_id,$product_name,1,$product_price)->asseociate('App\Models\Product');
session()->flash('success_message','Item added in Cart');
return redirect()->route('product.cart');
}
cart-component.blade.php
<div class=" main-content-area">
<div class="wrap-iten-in-cart">
#if(session::has('success_message'))
<div class="alert alert-success">
<strong>Success</strong>{{Session::get('success_message')}}
</div>
#endif
#if(Cart::count()>0)
<h3 class="box-title">Products Name</h3>
<ul class="products-cart">
#foreach(Cart::content() as $item)
<li class="pr-cart-item">
<div class="product-image">
<figure><img src="{{('assets/images/products')}}/{{$item->image}}" alt="{{$item->model->name}}"></figure>
</div>
<div class="product-name">
<a class="link-to-product" href="{{route('product.details',['slug'=>$item->model->slug])}}">{{$item->model->name}}</a>
</div>
<div class="price-field produtc-price"><p class="price">Rs.{{$item->model->regular_price}}</p></div>
<div class="quantity">
<div class="quantity-input">
<input type="text" name="product-quatity" value="{{$item->qty}}" data-max="120" pattern="[0-9]*" >
<a class="btn btn-increase" href="#"></a>
<a class="btn btn-reduce" href="#"></a>
</div>
</div>
<div class="price-field sub-total"><p class="price">Rs.{{$item->subtotal}}</p></div>
<div class="delete">
<a href="#" class="btn btn-delete" title="">
<span>Delete from your cart</span>
<i class="fa fa-times-circle" aria-hidden="true"></i>
</a>
</div>
</li>
#endforeach
</ul>
#else
<p>No Item In Cart</p>
#endif
</div>

Retrive ids and check related boxes

Using
Laravel 8.54
Livewire 2.6
Laratrust package for roles and permissions
I want to edit the permissions role like that
RolesEdit.php (livewire component)
<?php
namespace App\Http\Livewire\Admin\Roles;
use App\Models\Role;
use Livewire\Component;
use App\Models\Permission;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
class RolesEdit extends Component
{
public $data = [];
public $role;
public $selectedIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
}
public function update()
{
$this->data['permissions'] = $this->selectedIds;
$validated = Arr::except($this->validatedData(), ['permissions']);
$this->role->update($validated);
$this->role->permissions()->sync($this->data['permissions']);
}
public function validatedData()
{
return Validator::make($this->data, [
'display_name' => 'required',
'description' => 'required',
"permissions" => "required|array|min:1",
"permissions.*" => "required|distinct|min:1",
])->validate();
}
public function render()
{
$permissions = Permission::all();
return view('livewire.admin.roles.roles-edit', compact('permissions'));
}
}
Roles-edit.blade.php
<div class="mt-1">
<label class="form-label">{{ __('site.display_name') }}</label>
<input wire:model="data.display_name" type="text" class="form-control" placeholder="Enter role name" />
</div>
<div class="mt-1">
<label class="form-label">{{ __('site.role_description') }}</label>
<textarea wire:model="data.description" type="text" class="form-control"
placeholder="Enter Description"></textarea>
</div>
<div class="row w-100">
#foreach ($permissions as $permission)
<div class="col-md-3">
<div class="form-check ms-5">
<input wire:model.defer="selectedIds" class="form-check-input" id="{{ $permission->name }}"
value="{{ $permission->id }}" type="checkbox"
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }} />
<label class="form-check-label" for="{{ $permission->name }}">
{{ $permission->display_name }}</label>
</div>
</div>
#endforeach
</div>
When I open roles-edit view I want to check boxes that have $permission->id related to role so I use
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
But it did not work … all checkboxes is unchecked
instead using code:
{{ $role->permissions->contains($permission->id) ? 'checked' : '' }}
try this
#if($role->permissions->contains($permission->id)) checked #endif
also try to add wire:key directive to the parent div of the input element
<div class="form-check ms-5" wire:key="input-checkbox-{{ $permission->id }}">
I suggest you, create an array to retrieve the permissions ids of the role
public $permissionsIds = [];
public function mount(Role $role)
{
$this->role = $role;
$this->data = $role->toArray();
$this->permissionsIds = $this->role->permissions()->pluck('id');
}
// in blade
#if(in_array($permission->id,$permissionsIds)) checked #endif

Aurelia custom element access data from child to parent view model

I am new to Aurelia and need help accessing values from custom element in another view.
I have a scenario where I would like to share input file for attachment in multiple forms. One of the approach I am taking is to create custom element for input files that can be shared with multiple forms in web application.
Below is my code:
Custom element called FilePicker which will be shared between multiple forms. In my Request paged I inserted the custom element called:
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
My requirement is to access property called validFiles which is an array. I would like to use values from validFiles to custom object in Request view model called formData['attachment']
TS:
import { customElement, useView, bindable, bindingMode } from 'aurelia-framework';
#customElement('file-picker')
#useView('./file-picker.html')
export class FilePicker {
#bindable accept = '';
#bindable multiple = false;
#bindable({ defaultBindingMode: bindingMode.twoWay }) files: FileList;
validFiles = [];
input: HTMLInputElement;
// Validate function for on change event to input file.
public filesChanged() {
if (!this.files) {
this.clearSelection();
}
if (this.files) {
this.processFiles();
}
}
// Trigger on button click
public triggerInputClick() {
this.input.click();
}
// Find value in array of object
private findValinArrObj(arr, key, val) {
return arr.map(function (v) { return v[key] }).indexOf(val);
}
// Process file for each new files uploaded via browser
private processFiles() {
if (this.files) {
for (let i = 0; i < this.files.length; i++) {
let findFile = this.findValinArrObj(this.validFiles, 'name', this.files.item(i).name);
if (findFile === -1) {
this.validFiles.push(this.files.item(i));
}
}
this.clearSelection();
}
}
// Remove file from fileNames and validFiles array
public removeByFileName(fileName) {
if (this.validFiles) {
for (let i = 0; i < this.validFiles.length; i++) {
if (this.validFiles[i].name === fileName) {
this.validFiles.splice(i, 1);
}
}
}
}
// Clear input file in DOM
private clearSelection() {
this.input.type = '';
this.input.type = 'file';
}
}
HTML:
<template>
<input type="file" accept.bind="accept" multiple.bind="multiple"
files.bind="files" ref="input"
style="visibility: hidden; width: 0; height: 0;">
<button class="btn btn-primary" click.delegate="triggerInputClick()">
<slot>Browse...</slot>
</button>
<ul class="list-group" if.bind="validFiles">
<li class="list-group-item" repeat.for="file of validFiles" style="padding: 0; border:none;">
${file.name} <span class="glyphicon glyphicon-remove text-danger" style="cursor: pointer;" click.delegate="removeByFileName(file.name)"></span>
</li>
</ul>
</template>
Parent View Model:
TS:
export class Request {
pageTitle: string = "Request Page";
title: string = '';
description: string = '';
businessValue: string = '';
emails: string = '';
formData: object = {};
public postData() {
this.formData['title'] = this.title;
this.formData['description'] = this.description;
this.formData['businessValue'] = this.businessValue;
this.formData['emails'] = this.emails;
this.formData['attachment'] = [];
console.log(this.formData);
}
}
HTML:
<template>
<require from="./request.css"></require>
<require from="../../resources/elements/file-picker"></require>
<div class="panel panel-primary">
<div class="panel-heading">${pageTitle}</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" value.two-way="title" class="form-control" id="title" placeholder="Brief one-line summary of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<input type="text" value.two-way="description" class="form-control" id="description" placeholder="Detailed description of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Business Value</label>
<div class="col-sm-10">
<input type="text" value.two-way="businessValue" class="form-control" id="description" placeholder="Description of how this offers business value">
</div>
</div>
<div class="form-group">
<label for="emails" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" value.two-way="emails" class="form-control" id="emails" placeholder="Provide email address">
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-sm-2 control-label">Attachment(s)</label>
<div class="col-sm-10">
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-default pull-right" click.trigger="postData()">Submit</button>
</div>
</div>
</form>
</div>
</div>
</template>
Any help is really appreciated. :)
You can set up two-way-binding on your Request view, to bind the validFiles in your child view (file-picker) to a variable in your parent view (Request):
request.html:
<file-picker valid-files.two-way="validFiles"></file-picker>
request.ts:
public validFiles: File[];
file-picker.ts:
#bindable
public validFiles: File[];
This way any changes made to the validFiles object in either the child or the parent will update the object in both viewmodels.

Forms in Pop yii

I tried to insert a form in Pop up..I used the partial method to redirect it.
I written the pop up code in my controller action.
And I need to insert a form there which I created through GII.
A got an out put but the form is outside the Pop Up..
Can anybody tell me hoe can I Achieve this....
Controller
public function actionpopup($id)
{
//$this->render('/offerEvents/Details',array(
//'model'=>OfferEvents::model()->findByAttributes(array('id'=>$id)), ));
$OfferEventsList = OfferEvents::model()->findAllByAttributes(array('id' => $id));
foreach($OfferEventsList as $Listdata)
{ $titnw=$Listdata['title']; $details=$Listdata['description'];
$discountper=$Listdata['discountper']; $discountperamt=$Listdata['discountperamt'];
$strdaate=$Listdata['startdate']; $enddaate=$Listdata['enddate']; $evoftype=$Listdata['type']; }
$cmuserid=$Listdata['createdby'];
if($Listdata['createdby']==0){ $createdbyname="Admin"; } else { $createdbyname=$Listdata->company->companyname; }
$locationnw=$Listdata->location;
$offrimage=$Listdata->image;
if($offrimage!=""){ $imgUrls=$offrimage; } else { $imgUrls='image-not-available.png'; }
$infowinimgpaths='theme/images/OfferEvents/orginal/'.$imgUrls;
if (file_exists($infowinimgpaths)) { $infowinimgpathSrcs=Yii::app()->baseUrl.'/'.$infowinimgpaths; } else
{ $infowinimgpathSrcs=Yii::app()->baseUrl.'/theme/images/OfferEvents/image-not-available.png'; }
if (Yii::app()->user->id!='' && Yii::app()->user->id!=1){
$subcribeemailid=Yii::app()->user->email; $logsts=1;
$countsubscribe = Newsfeeds::model()->countByAttributes(array('emailid' => $subcribeemailid,'cuserid' => $cmuserid));
} else { $subcribeemailid=''; $countsubscribe=0; $logsts=0; }
$PopupdetailText='<div class="modal-dialog-1">
<div class="modal-content">
<div class="modal-header login_modal_header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h2 class="modal-title" id="myModalLabel">'.$titnw.' </h2>
</div>
<div class="container-1">
<div class="row">
<div class="col-sm-7 detail-text">
<h2 class="title"> ';
if($evoftype==0){ $PopupdetailText.='Offer Price: '.$discountperamt.'
<font style="font-size: 15px;">[ Up To '.$discountper.'% Discount ]</font>'; }
$PopupdetailText.='</h2><p>Details: </p>
<p>'.$details.'</p>
<p>Location: '.$locationnw.'</p>
<p>Expires in: '.$enddaate.'</p>';
if($countsubscribe==0){
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success btn-xs" Onclick="subcribefeed('.$logsts.','.$cmuserid.')" >Subscribe NewsFeed</button></p>';
} else {
$PopupdetailText.='<p>Shared by: '.$createdbyname.'
<button type="button" class="btn btn-success disabled btn-xs" >Already Subscribed NewsFeed</button></p>';
}
$PopupdetailText.='<div class="form-group" id="subcribefrm" style="display:none;background-color: #eee; padding: 12px; width: 82%;">
<input type="text" id="subemailid" placeholder="Enter EmailID here" value="'.$subcribeemailid.'" style="width: 100%;" class="form-control login-field">
<br/>
Subscribe Feeds </div> ';
// if($evoftype==0){ $PopupdetailText.='<p>Offer Price:<b> $'.$discountperamt.'</b></p>'; }
$PopupdetailText.='<p>
<img src="'.Yii::app()->baseUrl.'/theme/site/images/yes.png"/>Yes
<img src="'.Yii::app()->baseUrl.'/theme/site/images/no.png"/>No
<img src="'.Yii::app()->baseUrl.'/theme/site/images/comments.png"/>Comments
<img src="'.Yii::app()->baseUrl.'/theme/site/images/share.png"/>Share</p>
<br/>
<form>
<div class="form-group">';
$userComment=new Comments;
$this->renderPartial('/comments/_form', array('model' => $userComment));
$PopupdetailText.='</div>
<div class="form-group">
<input type="text" id="username" placeholder="Enter the below security code here" value="" class="form-control login-field">
</div>
<div class="form-group">
<p><img src="'.Yii::app()->baseUrl.'/theme/site/images/capcha.png"/>Cant read? Refresh</p>
</div>
<div class="form-group">
Post Commets
</div>
</form>
</div>
<div class="col-sm-5">
<img src="'.$infowinimgpathSrcs.'" width="100%"/>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="modal-footer login_modal_footer">
</div>
</div>
</div>
<script>
function subcribefeed(staus,cid)
{
if(staus==0){
$("#subcribefrm").toggle(); }
else { subcribefeedAdd(cid); }
}
function subcribefeedAdd(cid)
{
subusremail=$("#subemailid").val();
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if (subusremail == "" || !re.test(subusremail))
{ alert("Invalid EmailID ."); }
else {
postData ={
"email" :subusremail,
"cid" :cid
}
$.ajax({
type: "POST",
data: postData ,
url: "'.Yii::app()->baseUrl.'/newsfeeds/create",
success: function(msg){
if(msg=="Success"){ showdetails('.$id.'); alert("news feed subscribe successfully."); }
else if(msg=="available"){ alert("Already subscribe News Feed for this Commercial user."); }
else { alert("Error ."); }
}
});
}
}
</script> ';
echo $PopupdetailText;
}
renderPartial has a 3rd parameter return. If you set that to TRUE it will return the rendered form instead of echoing it. You can use it as follows:
$PopupdetailText .= $this->renderPartial('/comments/_form', array('model' => $userComment), TRUE);