Codeigniter - Trying to count articles view - codeigniter

Im working with codeigniter and have a controller and 3 model functions to read, insert and update a column of table.
i want to get count of view from db and update it per each view!
but after the update an extra row added to table! with zero value for content_id.
please check once!
this is my controller:
public function daily_report($id="")
{
$counter=$this->home_model->counter($id);
if($counter)
{
$view=$this->home_model->counter($id)->row()->view;
$views=$view+1;
$this->home_model->update_counter($views,$id);
}
else{
$views=1;
$this->home_model->set_counter($views,$id);
}
}
This is the model functions:
public function counter($id)
{
$code=$id;
$lang=$this->session->userdata('lang');
$data = $this->db
->select('view')
->from('tbl_views')
->where("content_id",$code)
->where("language",$lang)
->get();
if ($data->num_rows() > 0) {
return $data;
}else{
return false;
}
}
public function set_counter($views,$id)
{
$data = array(
'content_id' => $id ,
'view' => $views,
'language'=>$this->session->userdata('lang')
);
$this->db->insert('tbl_views', $data);
}
public function update_counter($views,$id)
{
$data = array(
'view' => $views,
);
$this->db->where('content_id', $id);
$this->db->update('tbl_views', $data);
}

Related

delete image from desk and table in morph relation in laravel

i have many to many morph relation in laravel and i want to update model that have images in attachmnets table
my Specialization model
public function attachments()
{
return $this->morphToMany(Attachment::class, 'attachmentable');
}
my Attachment model
public function specializations()
{
return $this->morphedByMany(Specialization::class, 'attachmentable');
}
my attachmentables model
protected $fillable = [
'attachment_id',
'attachmentable_id',
'attachmentable_type',
'key',
];
my controller update function
public function updatee($request, $id){
if($request->hasfile('image')){
$image = $this->uploadImages($request->image , 'specialiations/images');
$specialization = Specialization::where('id',$id)->with('attachments')->first();
if($specialization != null){
$this->attachmentRepository->destroy($specialization->attachments[0]->id, $request);
try {
unlink(public_path().$request->file);
} catch (\Throwable $th) {
//throw $th;
}
}
$spec = $this->update($request->all(),$id,$request);
$specImage = $this->attachmentRepository->create(['file'=>$image]);
$att = $this->attachmentAbleRepository->create([
'attachment_id' => $specImage->id,
'attachmentable_id' => $spec->id,
'attachmentable_type' => 'App\Models\Specialization',
'key' => 'specialization',
]);
}
return $spec;
}
i have an error "Undefined array key 0" or "attempt [id]"

Laravel - How to update Input Array without deleting Sales Detail

In my Laravel-8 project, I have this controller for Input Field Array Update.
Controller:
public function update(UpdateSaleRequest $request, $id)
{
try {
$sale = Sale::find($id);
$data = $request->all();
$update['date'] = date('Y-m-d', strtotime($data['date']));
$update['company_id'] = $data['company_id'];
$update['name'] = $data['name'];
$update['remarks'] = $data['remarks'];
$sale->update($update);
SaleDetail::where('sale_id', $sale->id)->delete();
foreach ($data['invoiceItems'] as $item) {
$details = [
'sale_id' => $sale->id,
'item_id' => $item['item_id'],
'employee_id' => $item['employee_id'],
'quantity' => $item['qty'],
'price' => $item['cost'],
'total_price' => $item['cost'] * $item['qty'],
'sale_type_id'=>$item['sale_type_id']
];
$saleDetail = new SaleDetail($details );
$saleDetail->save();
}
} catch (JWTException $e) {
throw new HttpException(500);
}
return response()->json($sale);
}
In the form, the user can add more Sales Detail or remove.
Some of the SaleDetail fields are being used somewhere else.
Is there a way to update the input field array without deleting the SaleDetail as shown in what I did here:
SaleDetail::where('sale_id', $sale->id)->delete();
Thanks
I've tried to restructure your code so that's easier to edit. I've left some comments. I can really recommend refactoring.guru. There you will find many ways to improve your code so that it is more extensible, maintainable and testable. If you have any questions, please feel free to ask.
class Sale extends Model
{
// Use a relationship instead of building your own query
public function details() {
return $this->hasMany(SaleDetail::class);
}
}
class SaleDetail extends Model
{
// Use a computed property instead of manually calculating total price
// You can access it with $saleDetail->totalPrice
public function getTotalPriceAttribute() {
return $this->price * $this->quantity;
}
}
class UpdateSaleRequest extends Request
{
public function authorize() {
return true;
}
protected function prepareForValidation() {
$this->merge([
// Create a Carbon instance by string
'date' => Carbon::make($this->date)
]);
}
public function rules() {
// Your validation rules
// Please also validate your invoice items!
// See https://laravel.com/docs/8.x/validation#validating-arrays
}
}
// We let Laravel solve the sale by dependency injection
// You have to rename the variable name in ihr web.php
public function update(UpdateSaleRequest $request, Sale $sale)
{
// At this point, all inputs are validated!
// See https://laravel.com/docs/8.x/validation#creating-form-requests
$sale->update($request->validated());
// Please ensure, that all properties have the same name
// In your current implementation you have price = cost, be consistent!
foreach($request->input('invoiceItems') as $invoiceItem) {
// How we can consider that a detail is already created?
// I assume that each item_id will only occur once, otherwise you'll
// place the id of each detail in your update form (e.g. in a hidden input)
$candidate = $sale->details()
->where('item_id', $properties['item_id'])
->first();
if($candidate) {
$candidate->update($properties);
} else {
$sale->details()->create($properties);
}
}
// A JWT-Exception should not be necessary, since your authentication
// will be handled by a middleware.
return response()->json($sale);
}
I have not tested the code, few adjustments may be needed.
Laravel has a method called updateOrCreate as follow
/**
* Create or update a record matching the attributes, and fill it with values.
*
* #param array $attributes
* #param array $values
* #return \Illuminate\Database\Eloquent\Model|static
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values)->save();
});
}
That means you could do some thing like
public function update(UpdateSaleRequest $request, $id)
{
try {
$sale = Sale::find($id);
$data = $request->all();
$update['date'] = date('Y-m-d', strtotime($data['date']));
$update['company_id'] = $data['company_id'];
$update['name'] = $data['name'];
$update['remarks'] = $data['remarks'];
$sale->update($update);
foreach ($data['invoiceItems'] as $item) {
$details = [
'item_id' => $item['item_id'],
'employee_id' => $item['employee_id'],
'quantity' => $item['qty'],
'price' => $item['cost'],
'total_price' => $item['cost'] * $item['qty'],
'sale_type_id'=>$item['sale_type_id']
];
$sale->saleDetail()->updateOrCreate([
'sale_id' => $sale->id
], $details);
}
} catch (JWTException $e) {
throw new HttpException(500);
}
return response()->json($sale);
}
I would encourage you to refactor and clean up your code.You can also read more about it here https://laravel.com/docs/8.x/eloquent#upserts

Restriction for not allowing same email and password in the database for my signup form

i want to make a restriction in my signup form which the user cant signup with the already exists email and password..
in my controller:
i already make a rules or callback
array(
'field' => 'txt_email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_check_if_valid_email|trim',
),
check_if_valid:
public function check_if_valid_email()
{
$where = array('email' =>$this->input->post('txt_email'),'password' =>$this->input->post('txt_password'));
$this->load->model('database_model');
if ($user = $this->database_model->validate_user('user', $where))
{
foreach ($user as $row) {
$checkemail = $row->email;
$checkpassword = $row->password;
}
if ($checkemail == $this->input->post('txt_email')){
$this->form_validation->set_message('check_if_valid_email', 'Email already existed!');
return false;
}
else
{
if ($checkpassword = $this->input->post('txt_password'))
{
$this->form_validation->set_message('check_if_valid_email', 'Email already exists!');
return false;
}
else
{
return true;
}
}
}
}
in my model:
public function validate_user($table, $where)
{
$this->db->where($where);
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
CodeIgniter's Form Validation library comes with the rule you're looking for, called: is_unique
http://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference
Your validation rules will look like this;
required|valid_email|is_unique[users.email]|trim
All you have to set it the table and column you want to be unique (users.email).
Hope this helps.

Laravel upgrade issue with whereHas

I recently changed versions of Laravel and I am now getting this error:
LogicException
Has method invalid on "belongsTo" relations.
Can anyone explain why I am now getting this error?
If I comment out the below three lines, no error.
Version: "laravel/framework": "4.1.7"
The piece of code in question is this:
$orderCount->whereHas('order', function($query) {
$query->whereRaw("status IN ('pending', 'prepaid')");
});
The entire controller logic here:
public function show($id) {
// the fields we want back
$fields = array('id', 'title', 'description', 'msrp', 'brand_id', 'category_id');
// how many products are in pending orders
$orders = 0;
// assume not admin must be display = 1
$display = 1;
// if logged in add more fields
if(Auth::check()) {
// add these fields to the query if dealer
array_push($fields, 'price_dealer', 'quantity');
// if admin add these fields
if (Session::get("admin")) {
$display = 0;
array_push($fields, 'cost', 'display', 'crate_quantity_threshold', 'price_crate');
}
}
$product = Product::with('images', 'brand', 'category', 'docs')
->select($fields)
->where('display', '>=', $display)
->find($id);
if(Auth::check()) {
// make orders obj
// we need to see how many orders
// there are pending for this product
$obj = new OrderItem;
$orderCount = $obj->newQuery();
$orderCount->where('product_id', '=', $id);
$orderCount->whereHas('order', function($query) {
$query->whereRaw("status IN ('pending', 'prepaid')");
});
$product->orders = $orderCount->sum('quantity') > 0 ? $orderCount->sum('quantity') : 0;
// dd(\DB::getQueryLog());
}
if ($product) {
return Response::json(array(
'product' => json_decode($product)
),
200
);
} else {
return Response::json(array(
'flash' => "Not found"
),
500
);
}
}
In Order model:
public function products()
{
return $this->belongsToMany('Product', 'order_items', 'order_id', 'product_id');
}
Short answer: Upgrade to 4.1.11+ due to:
4.1.7 - not implemented method
4.1.11 - method in place

cakePHP form custom validation

Hi all I'm creating an invoice system and trying to make sure that the person sending the request, is sending it to a person who exists. The code that I currently have isn't working and was wondering if someone could give me a hand.
model
'exists'=>array(
'rule'=>'partytwo',
'message'=>'That username doesnt exist.'
));
function userExists($field=array(), $compare_field=null )
{
if($field['exists']= $compare_field)
return TRUE;
else return FALSE;
}
and the validation in relationship the controller
if($this->request->is('post')){
if($this->Relationship->validates(array('fieldlist'=>array('partywo','Relationship.userExists')))){
$this->Relationship->create();
if ($this->Relationship->save($this->request->data))
{
$id=$this->Relationship->id;
$this->Session->setFlash('The relationship has been saved');
}}
else { $this->Session->setFlash('The relationship could not be saved. Please, try again.'); }
}
here is my current model
<?php
class Relationship extends AppModel{
var $name='Relationship';
public $useTable = 'relationships_users';
public $primaryKey = 'id';
var $validate = array(
'date' => array(
'rule' => array('datevalidation', 'systemDate' ),
'message' => 'Current Date and System Date is mismatched'),
'partytwo'=>array(
'partytwoExists'=>array(
'rule'=> 'userExists',
'message'=>'That username doesnt exist.'
)));
function datevalidation( $field=array(), $compare_field=null )
{
if ($field['date'] > $compare_field)
return TRUE;
else return FALSE;
}
function userExists($check)
{
$userExists= $this->find('count', array('conditions'=>$check));
if($userExists == 1)
{return TRUE;
}
else
return FALSE;
}
}
its currently going straight to errors
Have you read the book on validation?
// MODEL
var $validation = array(
'field_name' => array(
'rule' => array( 'customFunction', param ),
'message' => 'Message here'
)
);
function customFunction($field=array(), $compare_field=null )
{
if($field['exists'] == $compare_field)
return TRUE;
else return FALSE;
}
And for controller:
// CONTROLLER
if($this->request->is('post')){
$this->Relationship->set( $this->request->data );
if($this->Relationship->validates(array('fieldlist'=>array('partywo','Relationship.userExists')))){
$this->Relationship->create();
if ($this->Relationship->save($this->request->data))
{
$id=$this->Relationship->id;
$this->Session->setFlash('The relationship has been saved');
}
} else {
$this->Session->setFlash('The relationship could not be saved. Please, try again.');
}
}
It is something along those lines, try that.

Resources