I have a simple form, one of the fields is 'resource'. I have an Item model which has many Resources. I'm trying to save both the Item and it's Resource from my form.
Item.php:
public function resource()
{
return $this->hasMany('App\Resource');
}
public function addResource(Resource $resource)
{
return $this->resource->save($resource);
}
Resource.php:
public function item()
{
return $this->belongsTo('App\Item');
}
My save method in ItemsController:
public function store(CreateItemRequest $request)
{
//get and save Item
$item = new Item($request->all());
Auth::user()->item()->save($item);
//get and save Resource
$resource = new Resource(array($request->input('resource')));
$item->addResource($resource);
return view('items.index');
}
When calling addResource on the Item model, I get this error:
BadMethodCallException in Macroable.php line 81:
Method save does not exist.
in Macroable.php line 81
at Collection->__call('save', array(object(Resource))) in Item.php line 41
at Item->addResource(object(Resource)) in ItemsController.php line 73
at ItemsController->store(object(CreateItemRequest))
at call_user_func_array(array(object(ItemsController), 'store'), array(object(CreateItemRequest))) in Controller.php line 76
I've been stuck on this for way too long! Any help would be MUCH appreciated. I'm sure it's a simple newbie mistake...
Your addResource() method should look like this:
public function addResource(Resource $resource)
{
$this->resource()->attach($resource->id);
}
The property $this->resource will be resolved to an actual instance of a related model. If no models have yet been related it will evaluate to null. The method $this->resource() will actually return the type of relationship that exists between the models (in this case, it should return Illuminate\Database\Eloquent\Relations\HasMany).
Related
I'm making CRUD, with upload a file (image), but when I want to use unlink to delete the file I got an error, here's below.
Codeigniter4 error: Call to undefined method CodeIgniter\Database\MySQLi\Builder:: find()
This is the codes I used to try to delete the image file. From controller connect to model.
The controller:
public function delete()
{
$model = new Datatablesmodal();
$id = $this->request->getPost('product_id');
$model->deleteProduct($id);
return redirect()->to('/modalboot');
}
The modal:
public function deleteProduct($id)
{
$foto=$this->db->table("formulir_pendaftaran")->find(array('product_id' => $id)); (line 1)
unlink('/pasfoto/'.$foto['pas_foto']); (line 2)
$this->db->table('formulir_pendaftaran')->delete(array('product_id' => $id));
return $query;
}
The id of the table is product_id, if I deleted line 1 and 2 I can delete the data from the table but not the image file it's still in my directory, if I used line 1 and 2 to delete the file I can't because there is an error.
Exception says that $db dosn't have a method called find().
It's because you don't use a Model, you use Query Builder in $this->db->table().
In that way you should use a method getWhere(array('product_id' => $id)) instead of find(array('product_id' => $id));.
But best way to that what you want is creating a Model which corresponds to table named formulir_pendaftaran, and then use this model to delete self.
class FormulirPendaftaran extends Model
{
protected $table = 'formulir_pendaftaran';
protected $primaryKey = 'product_id';
protected $useAutoIncrement = true;
}
and then your model automaticly have a CRUD's method from Model, and you could use delete() method on that model:
$model = new FormulirPendaftaran();
$model->find($id)->delete();
and this will delete your instance of $id from Database, but if you want also delete the image you need to extends delete() method in your Model:
public function delete()
{
// your code to delete the image.
parent::delete(); //which delete your instance from DB
}
After setting up a controller and a view to show a specific entry from my database, I wanted to use laravels function of Route Model Binding to fetch the data fromn the database and pass it to the view. However I am getting following error:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with
message "Argument 2 passed to
Symfony\Component\HttpFoundation\RedirectResponse::__construct() must
be of the type integer, array given, called in
C:\xampp\htdocs\laravel\Cyberchess\vendor\laravel\framework\src\Illuminate\Routing\Redirector.php
on line 203"
I've tried to add this line to TrustProxy:
protected $headers = Request::HEADER_X_FORWARDED_ALL;
as the internet recommended, but when I opened the file, I realised it was already in the code.
My create/store works properly, which is why I assume it has something to do with Route Model Binding. I'm currently using a getRouteKeyName() to change the Key to 'AccID' so it should work.
//my controller
public function show(account $account){
//$account = account::where(['AccID' => $account])->get();
//dd($account);
return redirect('user.show', compact('account'));
}
//my model
class account extends Model
{
public function getRouteKeyName() {
return 'AccID';
}
public $timestamps = false;
}
//my view
<h1 class="title">Your Profile</h1>
<p>{{ $account->Nick }}</p>
I expected it to work just fine(duh), but got said error. When I dd(); the data, it has the information I want inside #attributes and in #original.
If if comment the dd() and let the return do it's work, I get the error.
The redirect() helper function is used to send a redirect 301 response from the server, what you want instead is to return a view like so
public function show(account $account)
{
$account = account::where(['AccID' => $account])->get();
return view('user.show', compact('account'));
}
The table distributor_requisition_items has the columns :requisition_id,product_id ,measuring_unit_id,quantity
In the model DistributorRequisition.php, I have:
class DistributorRequisition extends Model
{
public function items()
{
return $this->belongsToMany('App\Product','distributor_requisition_items',
'requisition_id','product_id')->withPivot('measuring_unit_id','quantity');
}
}
In the controller I have :
class CurrentInventoryController extends Controller
{
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::get();
$distributor_requisitions_all= $distributor_requisition->items;
// this line produces an error
return view('admin.current_inventory.distributor-inventory',
compact('distributor_requisitions_all','stores',.....));
}
}
In the distributor-inventory.blade.php, I have :
#foreach($distributor_requisitions_all as $aP)
{{$aP->items->measuring_unit_id}}
#endforeach
I get the following error :
Exception in Collection.php line 1527: Property [items] does not exist on this collection instance.
in Collection.php line 1527 at Collection->__get('items') in CurrentInventoryController.php line 64
And the line 64 in the controller has :
$distributor_requisitions_all= $distributor_requisition->items;
So how to use the eloquent model method items in the controller so that I can access the distributor_requisitions_all variable in the view to extract values from it ?
use with() method instead of get().
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::with('items');
return view('admin.current_inventory.distributor-inventory', ['distributor_requisitions_all' => $distributor_requisition]);
}
$distributor_requisition=DistributorRequisition::get(); is a collection of Model DistributorRequisition, while items is a method inside the model that is why it is giving you an error .. you can't directly call a Model method from a collection .. and to solve your issue what you have to do is
in your function
public function distributor_inventory(Request $request)
{
$distributor_requisition=DistributorRequisition::get();
return view('admin.current_inventory.distributor-inventory',
compact('distributor_requisition','stores',.....));
}
and in your view
#foreach($distributor_requisition as $aP)
// {{ $aP->items->measuring_unit_id }}
// that will give you error since $aP->items is another collection of many model item what you can do is add another loop
#foreach($aP->items as $item)
$item->pivot->measuring_unit_id }}
#endforeach
#endforeach
I am trying to set up a relationship with a project I am working on. The error I get is:
BadMethodCallException in Macroable.php line 81:
Method Organization does not exist.
Here is my store method.
public function store(Request $request)
{
$calendar_event = new CalendarEvent();
$calendar_event->title = $request->input("title");
$calendar_event->start = $request->input("start");
$calendar_event->end = $request->input("end");
$calendar_event->is_all_day = $request->input("is_all_day");
$calendar_event->background_color = $request->input("background_color");
$request->Organization()->calendar()->save($calendar_event);
return redirect()->route('calendar_events.index')->with('message', 'Item created successfully.');
}
My relationship in my CalendarEvent model is set up like this
public function Organization()
{
return $this->belongsTo('App\Organization');
}
The relationship in my Organization model is set up like this
public function calendar()
{
return $this->hasMany('App\CalendarEvent');
}
Thank you for your help.
Did you setup a route model binding? And even with that setup, i don't think you can access the model just from the request, you need to setup a proper parameter for the model you want injected.
public function store(Request $request, YourModel $model) {
}
Or the problem is that you are trying to save on $request, when you need to do that on $calendar_event, like this:
$calendar_event->Organization()->calendar()->save($calendar_event);
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 9 years ago.
I am fairly new to Yii and while trying to make a blog application of my own I made this function to add a comment to my post.
However, I have done everything according to theory but still am getting a :
Fatal error: Call to a member function addComment() on a non-object in /htdocs/blog/protected/controllers/PostController.php on line 63
My Post.php model class has this function :
public function addComment($comment){
$comment->tbl_post_id = $this->id;
return $comment->save();
}
And my PostController.php has these two function, one for creating the comment and the other one for altering the view file.
public function actionView($id)
{
$post=$this->loadModel($id);
$comment=$this->createComment($post);
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
)); }
protected function createComment($post)
{
$comment=new Comment;
if(isset($_POST['Comment']))
{
$comment->attributes=$_POST['Comment'];
if($post->addComment($comment)) // **This is line 63**
{
Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added." );
$this->refresh();
}
}
return $comment;
}
So logically I am calling the member function addComment inside the Post Model class using $post->addComment, and all the member functions of a model are initialized right? And logicaly shouldn't this be correct right? However, I am getting the above fatal error.
What am I doing wrong?
Any help would be appreciated.
Regards,
P.S - I am sorry if I am doing something really stupid.
$post isn't an object since you don't declare it anywhere
protected function createComment($issue)
{
$comment=new Comment;
if(isset($_POST['Comment']))
{
$comment->attributes=$_POST['Comment'];
if($post->addComment($comment)) // **This is line 63**
{
Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added." );
$this->refresh();
}
}
return $comment;
}
on line 63 he's searching for a variable named $post that does not exist. You have to create it or load from db like you're doing into your actionView()
$post=$this->loadModel($id);
Obviously for load it, you need $id that has to be passed to your createComment() function
You have addComment() method in Post Model Class. So, You can handle this method by the Object of Post Model class from any of your controller.
Your declaration
$post->addComment($comment)
is Correct but there is no $post object. So Just create instance of Post Model as
$post=new Post();
Finally your code should be like
if(isset($_POST['Comment']))
{
$comment->attributes=$_POST['Comment'];
$post=new Post();
if($post->addComment($comment)) // **This is line 63**
{
Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added." );
$this->refresh();
}
}