Unable to resolve dependency [Parameter #0 [ <required> $task ]] - php

I have a main Blade where I call the modal that is in another Blade, but I need to pass the information of each task to it. The modal is inside a foreach loop foreach($tasks as $task), then comes the taskmodal component, then a card with the information to open the modal.
I'm trying to pass a parameter from a blade to a modal on another blade
Add component to tasks.blade.php
#foreach ($tasks as $task)
#livewire('componentes.taskmodal',['task'=>$task])
#endforeach
then on the Taskmodal component
<?php
namespace App\Http\Livewire\Componentes;
use Livewire\Component;
class Taskmodal extends Component
{
public $columnTask;
public $modalviews;
public $active;
public $task;
public function updateView($view){
$this->modalviews = $view;
}
public function mount($task){
$this->columnTask = [1=>'Texto',2=>'Fecha'];
$this->modalviews = [[1,'Descripcion'],[1,'Subtareas'], [1,'Comentarios']];
$this->active = '2';
$this->task = $task;
}
public function add($item){
array_push($this->columnTask, $item);
}
public function changeActive($item){
if($this->active != $item){
$this->active = $item;
}
}
public function render()
{
return view('livewire.componentes.taskmodal');
}
}
if i debug with dd($task['Titulo']) on the taskmodal blade it works
<div class="modal-top">
<h3 class="modal-title px-5" id="exampleModalLabel">#php dd($task['Titulo']); #endphp</h3>
</div>
but when
<div class="modal-top">
<h3 class="modal-title px-5" id="exampleModalLabel">{{$task['Titulo']}}</h3>
</div>
The error is Unable to resolve dependency [Parameter #0 [ $task ]]
Component $task
array:4 [▼
"id" => 1
"Hecho" => 1
"Titulo" => "Titulo 1"
"Info" => array:2 [▶]
]
"I did my best to write it in English, but it's not my primary language. I hope someone can help me
I've tried changing the names of the parameters, using a differents ways to pass de parameter.

Related

Why are some of my request parameters sent as `null` to my controller?

I'm developing a LiveWire/Laravel project and in my product.blade.php, the category_id is sent as null to the store function. Apparently there is no problem in my input and my model and category_id is defineded in my component.
I used some artisan comands related to clearing the cache and config and even I created another component with different name but I met same bug
dd:
array:8 [▼
"title" => "تراکت"
"en_title" => "tracket"
"category_id" => null
"description" => "nothing"
"status" => 1
"img" => null
"price" => "48000"
"keywords" => "tracket"
]
Livewire Product Blade:
<div class="form-group">
<label class="form-label">دسته بندی محصول</label>
<select wire:model="category_id" id="select-countries" class="form-control custom-select">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#if(count($category->childrenRecursive) >0)
#include('Admin.category.partials',['categories'=>$category->childrenRecursive,'level'=>1,'create'=>1])
#endif
#endforeach
</select>
</div>
Livewire Component :
<?php
class Index extends Component
{
public $title,$en_title,$category_id,$description,$status=1,$img=null,$price,$keywords;
public function store(){
$keywords=serialize(explode(",",$this->keywords));
Product::create([
'title'=>$this->title,
'en_title'=>$this->en_title,
'category_id'=>$this->category_id,
'description'=>$this->description,
'status'=>$this->status,
'price'=>$this->price,
'image'=>$this->img,
'keywords'=>$keywords,
]);
$this->reset(['title','en_title','category_id','description','price']);
session()->flash('add_product','محصول شما با موفقیت اضافه شد');
}
public function render()
{
$categories=Category::with('childrenRecursive')->where('parent_id',null)->get();
$products=Product::latest()->paginate(8);
return view('livewire.admin.product.index',compact('categories','products'))->extends('layouts.admin')->section('content');
}
}
Your syntax appears correct and I suspect you're sometimes seeing null because you're not setting an initial value for $category_id. Therefore, if you don't select an option from your select element and submit your form, the value of $category_id will be null.
You can perform some component initialization in the mount method where I suggest you set an initial value for your public properties:
public $categories, $products;
public $category_id;
public function mount()
{
$this->categories = Category::with('childrenRecursive')
->where('parent_id', null)
->get();
$this->products = Product::latest()->paginate(8);
$this->category_id = $this->categories->first()->id;
}
public function render()
{
return view(
'livewire.admin.product.index',
compact('categories','products')
)
->extends('layouts.admin')
->section('content');
}

How Can I Query Polymorphic Relationship in Laravel 8

I am able to create and even delete a polymorphic row from my app, but I can not for the life of me able to figure out how to query the relationship so I can update the row. My models and controller methods are below--all work except for public function updateManifest($id). I didn't include all the update code I've been trying over the past day and a half because it would be too much and not really relevant, but I can tell you that I can only get as deep as the Workorder model, I can't seem to query anything related through the poly relationship so I can query all the manifest objects. Thank you.
Workorder.php
class Workorder extends Model
{
...
public function manifest(){
return $this->morphMany(Manifest::class, 'manifestable');
}
}
Manifest.php
class Manifest extends Model
{
use SoftDeletes;
protected $fillable = [
'stream_id', 'manifest_number', 'manifest_quantity', 'manifest_rate',
'manifest_total', 'manifestable_id', 'manifestable_type', 'stream_description_plus'
];
public function manifestable(){
return $this->morphTo();
}
}
edit.php (Workorder controller)
class Edit extends Component {
public function mount(Workorder $workorder, Manifest $manifest)
{
$this->workorder = $workorder;
$this->manifest = $manifest->manifestable;
$this->workorder_number = $workorder->workorder_number;
$this->workorder_po_number = $workorder->workorder_po_number;
$this->workorder_status = $workorder->workorder_status;
$this->workorder_job_notes = $workorder->workorder_job_notes;
$this->project_id = $workorder->project_id;
$this->customer_id = $workorder->customer_id;
$this->generator_id = $workorder->generator_id;
$this->prevailing_wage = $workorder->prevailing_wage;
$this->touched = false;
}
public function addManifest($id)
{
Manifest::create([
'workorder_id' => $this->workorder->id,
'stream_description_plus' => $this->stream_description_plus,
'manifest_number' => $this->manifest_number,
'manifest_quantity' => $this->manifest_quantity,
'manifest_rate' => $this->manifest_rate,
'manifestable_id' => $this->workorder->id,
'manifestable_type' => get_class($this->workorder)
]);
return redirect()->route('admin.workorder.edit', $this->workorder->id);
}
public function updateManifest($id)
{
$record = Workorder::find($id);
/* dd($record);*/
$record->update([
'stream_description_plus' => $this->stream_description_plus,
'manifest_number' => $this->manifest_number,
'manifest_quantity' => $this->manifest_quantity,
'manifest_rate' => $this->manifest_rate,
]);
return redirect()->route('admin.workorder.edit', $this->workorder->id);
}
public function deleteManifest($id)
{
$record = Manifest::findOrFail($id);
$record->delete();
return redirect()->route('admin.workorder.edit', $this->workorder->id);
}
public function render()
{
$items = Item::all();
$users = User::all();
$projects = Project::all();
$generators = Generator::all();
$customers = Customer::all();
$personnel = Personnel::all();
$streams = Stream::all();
return view('livewire.admin.workorders.edit',
compact('items', 'projects', 'generators',
'customers', 'personnel', 'users', 'streams'));
}
}
update form
...
<form wire:submit.prevent="updateManifest({{$man->id}})" method="PUT">
<div class="grid grid-cols-6 gap-6">
<div class="col-span-6">
<select wire:model="stream_id"
class="mt-1 form-select block w-full pl-3 pr-10 py-2 text-base leading-6 border-gray-300 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 sm:text-sm sm:leading-5">
<option value="">
Select Waste Stream
</option>
#foreach($streams as $stream)
<option value="{{$stream->id}}">{{$stream->stream_description}}</option>
#endforeach
</select>
#error('stream_description')
<span class="error">{{ $message }}</span>
#enderror
</div>
</form>
...

Type error: Argument 2 passed to Controller::show() must be an instance of modal, string given

Adding up and down voting functions to a classified page. Using Laravel, and Vue.
The error I get is:
(1/1) FatalThrowableError
Type error: Argument 2 passed to Hustla\Http\Controllers\ListingVoteController::show() must be an instance of Hustla\Listing, string given
I have included the vue file, the vote controller, the listing model, and the route. I was hoping someone could help me out.
Listing Model
public function votesAllowed()
{
return (bool) $this->allow_votes;
}
public function commentsAllowed()
{
return (bool) $this->allow_comments;
}
public function votes()
{
return $this->morphMany(Vote::class, 'voteable');
}
public function upVotes()
{
return $this->votes()->where('type', 'up');
}
public function downVotes()
{
return $this->votes()->where('type', 'down');
}
public function voteFromUser(User $user)
{
return $this->votes()->where('user_id', $user->id);
}
Vote Controller
public function show(Request $request, Listing $listing)
{
$response = [
'up' => null,
'down' => null,
'can_vote' => $listing->votesAllowed(),
'user_vote' => null,
];
if ($listing->votesAllowed()) {
$response['up'] = $listing->upVotes()->count();
$response['down'] = $listing->downVotes()->count();
}
if ($request->user()) {
$voteFromUser = $listing->voteFromUser($request->user())->first();
$response['user_vote'] = $voteFromUser ? $voteFromUser->type : null;
}
return response()->json([
'data' => $response
], 200);
}
Vote.vue
<template>
<div class="listing__voting">
<a href="#" class="listing__voting-button">
<span class="glyphicon glyphicon-thumbs-up"></span>
</a> 1
<a href="#" class="listing__voting-button">
<span class="glyphicon glyphicon-thumbs-down"></span>
</a> 2
</div>
</template>
<script>
export default {
data () {
return {
up: null,
down: null,
userVote: null,
canVote: false
}
},
props:{
listingId: null
}
}
</script>
Route
Route::get('/{location}/{listing}/votes',[
'uses' => '\Hustla\Http\Controllers\ListingVoteController#show'
]);
Your route definition has two parameters defined: {location} and {listing}. The parameters are passed to the controller method in the order in which they are defined.
Your controller method, however, is only defined to accept one route parameter. The first route parameter is what will be passed to the method, and in this route definition, that is the {location} parameter. Since {location} does not match $listing, the string value will be passed in, and you'll get the error you're seeing.
You need to add the second route parameter to your controller action:
public function show(Request $request, $location, Listing $listing)
{
// code
}
If $location is a model as well, you can go ahead and add the type hint to enable the implicit route model binding.

Persisting/Flushing a form created an extra row in the database

I have a form with multiple rows created from one table (no relationships to other tables). When I save the form, every change I've made is saved, but I do have an additional empty row in the database.
See below for (hopefully) all neccessary informations.
PropertyAdditionCostFrequency.php
/**
* #ORM\Entity
* #ORM\Table(name="property_addition_cost_frequency")
*/
class PropertyAdditionCostFrequency
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $label = '';
private $costFrequencyCollection;
public function __construct()
{
$this->costFrequencyCollection = new ArrayCollection();
}
// + the getters and setters
}
PropertyAdditionCostFrequencyLabelType.php
class PropertyAdditionCostFrequencyLabelType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('label' )
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => PropertyAdditionCostFrequency::class,
));
}
}
PropertyAdditionCostFrequencyForm.php
class PropertyAdditionCostFrequencyForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add( 'cost_frequency_collection', CollectionType::class, array(
'entry_type' => PropertyAdditionCostFrequencyLabelType::class,
'label' => ''
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => PropertyAdditionCostFrequency::class
]);
}
}
AdminCoreDataController.php
public function showCoreDataListAction( Request $request )
{
$PropertyAdditionCostFrequency = new PropertyAdditionCostFrequency();
$repository = $this->getDoctrine()->getRepository('AppBundle:PropertyAdditionCostFrequency');
$cost_frequency = $repository->findAll();
foreach ($cost_frequency as $k => $v) {
$PropertyAdditionCostFrequency->getCostFrequencyCollection()->add($v);
}
$form = $this->createForm( PropertyAdditionCostFrequencyForm::class, $PropertyAdditionCostFrequency);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$propertyAdditionCostFrequency_form = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($propertyAdditionCostFrequency_form);
$em->flush();
$this->addFlash('success', 'successfully changed the data');
return $this->redirectToRoute('admin_core_data');
}
return $this->render('logged_in/content/admin/core_data/core_data.html.twig', [
'propertyCostFrequencyForm' => $form->createView()
]);
}
core_data.html.twig
{{ form_start(propertyCostFrequencyForm) }}
<div class="row" id="cost_frequency_box">
{% for single_frequency in propertyCostFrequencyForm.cost_frequency_collection %}
<div class="row js-single-cost-frequency-box">
<div class="col-sm-1 js-delete-cost-frequency">
<a href="/admin/property/delete/5">
<i class="fa fa-trash"></i>
</a>
</div>
<div class="col-sm-4">
{{ form_widget(single_frequency.label) }}
</div>
</div>
{% endfor %}
</div>
<div class="row">
<div class="col-sm-3">
<button class="col-sm-12 btn btn-success" type="submit">Speichern</button>
</div>
</div>
{{ form_end(propertyCostFrequencyForm) }}
a dump() of $propertyAdditionCostFrequency_form right before '$em->persist($propertyAdditionCostFrequency_form)'
PropertyAdditionCostFrequency {#394 ▼
-id: null
-label: ""
-costFrequencyCollection: ArrayCollection {#395 ▼
-elements: array:4 [▼
0 => PropertyAdditionCostFrequency {#422 ▼
-id: 1
-label: "1"
-costFrequencyCollection: null
}
1 => PropertyAdditionCostFrequency {#424 ▼
-id: 2
-label: "2"
-costFrequencyCollection: null
}
2 => PropertyAdditionCostFrequency {#425 ▼
-id: 47
-label: "3"
-costFrequencyCollection: null
}
3 => PropertyAdditionCostFrequency {#426 ▼
-id: 38
-label: "4"
-costFrequencyCollection: null
}
]
}
}
The reason why this is happening is evident from the dump you have posted: the top level PropertyAdditionCostFrequency has the id set to null, so of course it is going to create a new row for that, so if you were simply wondering why it creates a new row thats your reason :).
On the other hand I can't help but think, you have misunderstood how symfony forms / doctrine works, UNLESS having multiple child PropertyAdditionCostFrequency added to one parent PropertyAdditionCostFrequency is the desired effect.
IF it is not the desired effect and you simply want to create a form which contains a form for every entry of PropertyAdditionCostFrequency in the database(which I would not recommend, because once the DB gets big, it won't be very efficient), you can just use createFormBuilder method inside the controller, add an arbitrary CollectionType field (i.e. $builder->add('frequencies', CollectionType::class), then just create an array and assign the result of findAll() to a key(key name should correspond to the field name, in this case, 'frequencies') and finally set that as the data for the form you have just created (use $builder->getForm() method to get the form, since thats what you want in the controller and you should use the set data method on that :)) (P.S. these are just rough guidelines, I'm not sure, that I haven't missed anything)

Display name of select form rather than it's Id (error:Trying to get property of non-object) laravel 5

I have 2 tables tn_client and tn_project, which project have 1 client while client can have many projects, rather than displaying client id on my table, i want display its client name but when i did that its said trying to get property of non-object.
Trying to get property of non-object (View:
C:\xampp\htdocs\PKL\netxcel-activityreport-11b90b878d39\resources\views\project.blade.php)
Above is the full error that i get, and below is the tables
tn_project
tn_client
CONTROLLER
public function index(){
Log::info('Entering index');
return view('project')
->with('title','Project')
->with('projects',Project::with('client','invoice')->get())
->with('clients',Client::all())
->with('invoices', Invoice::all());
}
//get all data
public function getAll(){
return Response::json(
array(
'content' => Project::with('client','invoice')->get(),
'status' => 'success',
)
);
}
public function createOrEdit(){
$currentUsername = Auth::user()->name;
$isUpdate = false;
$projectId = Input::get('prevId');
//populate data
$project = new Project;
if($projectId != ""){
$project = Project::where('cv_id','=',$projectId)->firstOrFail();
$project->cv_updated_by = $currentUsername;
$project->cn_updated_at = Carbon::now();
$isUpdate = true;
} else{
$project->cv_created_by = $currentUsername;
$project->cn_created_at = Carbon::now();
}
$project->cv_id = Input::get('projectId');
$project->cv_name = Input::get('projectName');
$project->cv_client_id = Input::get('clientId');
$project->cn_invoice_method = Input::get('invoiceId');
$project->cn_project_rate = Input::get('projectRate');
$project->cn_note = Input::get('note');
//execute
if($isUpdate){
Log::info("entering update mode");
Project::where('cv_id','=',$projectId)->update(['cv_id'=>$project->cv_id,
'cv_name'=>$project->cv_name,
'cv_client_id'=>$project->cv_client_id,
'cn_invoice_method'=>$project->cn_invoice_method,
'cn_project_rate'=>$project->cn_project_rate,
'cn_note'=>$project->cn_note,
'cn_updated_at'=>$project->cn_updated_at,
'cv_updated_by'=>$project->cv_updated_by]);
}else{
$project->save();
}
return Response::json(
array(
'content' => Project::with('client','invoice')->get(),
'status' => 'success',
)
);
}
Model
PROJECT
<?php
namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Project extends Model {
protected $table = 'tn_project';
public $timestamps = false;
protected $fillable = [
'cv_id',
'cv_name',
'cv_client_id',
'cn_invoice_method',
'cn_project_rate',
'cn_note',
'cn_created_at',
'cv_created_by',
'cn_updated_at',
'cv_updated_by'
];
public function client(){
return $this->belongsTo('Activity\Client','cv_client_id','cn_id');
}
public function invoice(){
return $this->hasOne('Activity\Invoice','cn_id','cn_invoice_method');
}
}
CLIENT
<?php
namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Client extends Model {
protected $table = 'tn_client';
public $timestamps = false;
protected $fillable = [
'cv_name',
'cv_contact',
'cv_email',
'cv_phone',
'cv_address',
'cn_created_at',
'cn_created_by',
'cn_updated_at',
'cn_updated_by'
];
public function project(){
return $this->hasOne('Activity\Project', 'cv_id', 'cn_id');
}
}
VIEW
this is my select form
<div class="col-md-9">
<select name="clientId" id="clientId" class="form-control" placeholder="Select Client">
#foreach ($clients as $client)
<option value='{{$client->cn_id}}'>{{$client->cv_name}}</option>;
#endforeach
</select>
</div>
This is how i called the function to display it in my view
#foreach($projects as $project)
<tr class="odd gradeX">
<td>{{$project->cv_id}}</td>
<td>{{$project->cv_name}}</td>
<td>{{$project->client->cv_name}}</td><!--This is what cause an -->
<td>{{$project->cn_invoice_method}}</td>
<td>{{$project->cn_project_rate}}</td>
<td>{{$project->cn_note}}</td>
<td>
<a class="btn btn-success" title="edit" data-id={{$project->cv_id}} data-action="project-edit"><i class="fa fa-pencil"></i></a>
<a class="btn btn-danger" title="delete" data-id={{$project->cv_id}} data-action="project-delete"><i class="fa fa-times"></i></a>
</td>
</tr>
#endforeach
im still new to laravel, and what did i do wrong that make such an error like that?
I found the answer, i got the reference from here so based on that reference and the basic of x->y->z, we got to check first that x->y have some value in it if yes we got to check whether it's an object or just an array, in my case it was an array so rather doing something like this
{{$project->client->cv_name}}
which is that how to display an object, we should do something like this
{{$project->client['cv_name']}}
and that is how you solve your problem, cheers :D

Categories