Call to undefined method CodeIgniter\Database\MySQLi\Builder:: find() - php

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
}

Related

Laravel 5.6 not saving field in `created` model event

I am trying to save a field from the created model event but for some reason the stripe_coupon_id column is never being saved. The created event does run as I've tested by trying a dd inside it and it does fire the event but just does not save that column.
class DiscountRate extends Model
{
public $table = "discount_rates";
public $primaryKey = "id";
public $timestamps = true;
public $fillable = [
'id',
'name',
'rate',
'active',
'stripe_coupon_id'
];
public static function boot()
{
parent::boot();
self::created(function ($discountRate) {
$coupon_id = str_slug($discountRate->name);
$discountRate->stripe_coupon_id = $coupon_id;
});
}
}
In my controller I simply call a service function which calls the default Laravel model create function:
public function store(DiscountRateCreateRequest $request)
{
$result = $this->service->create($request->except('_token'));
if ($result) {
return redirect(route('discount_rates.edit', ['id' => $result->id]))->with('message', 'Successfully created');
}
}
discount_rates table:
The created event is triggered after your model is created. In this case, you need to to call $discountRate->save() in the end in order to update the model which you just created.
As alternative, you can use creating event instead. In this case you don't need to call save() in the end because the model is not yet saved in your database.
A big difference in creating event is that the model does not have an id yet if you use auto-incrementing which is default behavior.
More info about events you can find here.
you have to set stripe_coupon_id before creating. So replace static::creating instead of self::created in boot method of DiscountRate model.

Laravel 5.6 Reverse HasManyThrough

I have the following table structure in my database:
products
id
product_formats
id
product_id
product_prices
id
product_format_id
When I'm trying to do $this->format->product; inside my ProductPrice class, I get an error:
LogicException: App\ProductPrice::product must return a relationship instance.
When I perform a dd inside my function:
dd($this->format()->first()->product);
I get the instance of the product. However, removing the dd would still throw the exception.
Why am I getting the LogicException?
ProductPrice
class ProductPrice extends Model
{
public function format()
{
return $this->belongsTo(ProductFormat::class, 'product_format_id');
}
public function product()
{
return $this->format->product;
}
}
ProductFormat
class ProductFormat extends Model
{
public function product()
{
return $this->belongsTo(Product::class);
}
}
Update
The result of dd($this->format); returns an instance of ProductFormat.
After investigating the HasAttributes::getRelationshipFromMethod(), I've noticed that if the property does not exist in the properties attribute of the class, it will try to retrieve a relation, hence the error.
To fix it, I had to add the following to my class:
protected $attributes = ['product'];
Otherwise, I could call product as a function instead of attribute:
$price->product();

Groupby on relation laravel

Hey i have three table like this
--table plan--
id
name
....
----table letter---
id
plan_id
....
---table person----
id
plan_id
name
.....
Model i have :
---Model plan---
class plan extends Model
{
protected $table = 'plan';
public function letter(){
return $this->hasOne('App\letter');
}
public function person(){
return $this->hasMany('App\person');
}
}
--Model person--
class person extends Model
{
public function plan(){
return $this->belongsTo('App\plan');
}
}
--Model letter--
class letter extends Model
{
public function plan(){
return $this->belongsTo('App\plan');
}
}
And in controller i write code like this :
$letter = letter::find($id) // $id from url parameter and it's work
return view('letter',['letter' => $letter]);
Nah in view i wanna acces person name from letter model as distinct , so i write code like this
{{ #foreach ($letter->plan()->person()->groupBy('name')->get) as $person }}
but it return error like this :
Call to undefined method Illuminate\Database\Query\Builder::person()
Where is my mistake(s)?
There is a difference between $letter->plan() and $letter->plan. If you call it like a method, Laravel will return the Query Builder. If you call it like an attribute Laravel will return the model from that relation.
So you're trying to call your model on the Query Builder, which is a method that doesn't exists and creates the error. This will fix your problem:
$letter->plan->person()->groupBy('name')->get()
In your controller you can do:
$letter = letter::find($id) // $id from url parameter and it's work
$persons = $letter->plan->person()->groupBy('name')->get();
return view('letter', compact('letter', 'persons'));
And in your view:
#foreach($persons as $person)

eloquent: How to load and set model variables, inside the model itself?

Laravel documentation suggests the following way to set up an eloquent model:
$user = user::with($conditions)->first();
What if I want to set up my eloquent model inside the model itself:
$user = new user();
$user->setup($conditions);
// class definition
class user extends Eloquent{
public function setup($conditions){
// load current object with table data
// something like
$this->where($conditions)->first();
// previous line output is dangling, is ok to assign it to $this variable?
}
}
If you're extending from Eloquent model, you may try the following approach. I assume you have a unique id column.
public function setup($conditions)
{
$model = self::with($conditions)->first();
if (! is_null($model)) {
$this->exists = true;
$this->forceFill(self::find($model->id)->toArray());
}
return $this;
}
Hope this solve your issue.

Laravel/PHP: New Instance of Model Class within Method of This Model

New to Laravel and still fresh to OOP! I'm assuming this has more to do with OOP than strictly Laravel.
So my main problem is that I am trying to pass all rows from a database table called 'fin_income_category' via a method in my model called Income to a controller called PlannerController. To do this I have created a static method within Income called getIncomeCategories()
First of all, here is my __construct method within Income:
public function __construct($income, array $attributes = array()){
parent::__construct($attributes);
$this->table = $income;
}
And here is the getIncomeCategories method also within Income:
public static function getIncomeCategories(){
$category = new self('fin_income_category');
$categories = $category->all();
return $categories;
}
Finally, here is the edit($id) method within the PlannerController where I am to call this method and pass the categories along to my view. Note that only the first statement in this function is the one in question...the others work fine:
public function edit($id)
{
$income_categories = Income::getIncomeCategories();
$newIncome = new Income('fin_income');
$newRecord = $newIncome->where('id', '=', $id)->get();
return View::make('planner.edit', array('record'=>$newRecord, 'categories'=>$income_categories));
}
When I run the code like this I receive an error from Laravel:
ErrorException
Missing argument 1 for Income::__construct(),
called in /opt/lampstack/frameworks/laravel/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 615 and defined
In other cases where I have instantiated a new Income I have not received this error.
Change the getIncomeCategories() to this
public static function getIncomeCategories(){
$category = new self('fin_income_category');
return $category->get()->toArray();
}
The reason why your code didn't work is because the eloquent all() found in
Illuminate\Database\Eloquent\Model; the code snippet is found below
public static function all($columns = array('*'))
{
$instance = new static;
return $instance->newQuery()->get($columns);
}
is instantiating a static class which is bound to the called class which is your Income Model Class in your case, and in the process requesting the arguments in the constructor

Categories