How to add custom methods to Laravel Carbon - laravel

I've been searching this problem for 2 days but no luck. I want to add custom methods to laravel carbon. I use the syntax below:
namespace App\Http\Controllers\Helpers;
use Carbon\CarbonInterface;
interface CarbonJalaliInterface extends CarbonInterface {
public function toJalaliDateTimeString($unitPrecision = 'second');
public function toJalaliDateString($unitPrecision = 'second');
}
abstract class CarbonJalali implements CarbonJalaliInterface {
public function toJalaliDateTimeString($unitPrecision = 'second') {
list($part1, $part2) = explode(' ', $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)));
list($year, $month, $day) = explode('-', $part1);
list($hour, $minute, $second) = explode(':', $part2);
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
include_once ('jdf.php');
$jalali_date = jdate("H:i:s - Y/m/d",$timestamp);
return $jalali_date;
}
public function toJalaliDateString($unitPrecision = 'second') {
$timezone = 0;
list($part1, $part2) = explode(' ', $this->rawFormat('Y-m-d'));
list($year, $month, $day) = explode('-', $part1);
$timestamp = mktime($month, $day, $year);
include_once ('jdf.php');
$jalali_date = jdate("Y/m/d",$timestamp);
return $jalali_date;
}
}
But i get the error:
Symfony\Component\Debug\Exception\FatalErrorException DateTimeInterface can't be implemented by user classes
I want to use it like this :
CarbonJalali::now()->toJalaliDateTimeString();
Any suggestions? Thanks.

Related

How to use DB:: from helper class

I have a helper class name common.php in App\Helpers folder. I want to use DB:: facade here to use some db table. In helper method My code is -
<?php
use DB;
function ref_number()
{
$last_row = DB::table('model_table')->latest('id')->first();
if($last_row) {
$ref = explode('-', $last_row->ref);
if($ref[0] === date('y')) {
// if running year
$ref = $ref[1] + 1;
$ref = date('y') .'-'. $ref;
}
else{
$ref = date('y') .'-'. 1; // if new year
}
}
else{
$ref = date('y') .'-'. 1; // if first data
}
return $ref;
}
But this not working. Following error has been arrived.
So how can i solve this?
Change your using to: Illuminate\Support\Facades\DB;

Laravel belongsTo with condition and eager load

I have a Post model associated to a Section model, which depend on an extra condition to work:
<?php
class Post extends Base
{
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat')->where('website', $this->website);
}
}
When I want to retrieve a Post and get it's associated section, I can do it as:
$post = Post::first();
echo $post->section->name; // Output the section's name
However, when trying to get the section using an eager load:
Post::with(['section'])->chunk(1000, function ($posts) {
echo $post->section->name;
});
Laravel throw the following exception :
PHP error: Trying to get property of non-object
When I do a debug of a Post object returned by the above eager load query, I notice that the section relationship is null.
Note that it is working fine if I remove the condition from the belongsTo association.
Do you guys have any ideas why it's happening?
As mentioned in my comment, where shouldn't be used in the relationship definition. Hence, your relation definition is good with just
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat');
}
and you can eager load in this way (not giving out the exact query with chunk etc)
Post::with(['section' => function ($query) use ($request) {
$query->where('website', $request['website'])
}])->get()->first();
i.e. when you pass the variable website in request or else use any other variable in a similar way.
I hope that explains. Please add comments if anything is unclear.
You can achieve it by defining custom relationship.
BelongsToWith.php
<?php
declare(strict_types=1);
namespace App\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BelongsToWith extends BelongsTo
{
/**
* #var array [$foreignColumn => $ownerColumn, ...] assoc or [$column, ...] array
*/
protected $conditions = [];
public function __construct(array $conditions, Builder $query, Model $child, string $foreignKey, string $ownerKey, string $relation)
{
$this->conditions = $conditions;
parent::__construct($query, $child, $foreignKey, $ownerKey, $relation);
}
public function addConstraints()
{
if (static::$constraints) {
// Add base constraints
parent::addConstraints();
// Add extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$this->getQuery()->where($this->related->getTable() . '.' . $value, '=', $this->child->{$key});
}
}
}
public function addEagerConstraints(array $models)
{
// Ignore empty models
if ([null] === $this->getEagerModelKeys($models)) {
parent::addEagerConstraints($models);
return;
}
$this->getQuery()->where(function (Builder $query) use ($models) {
foreach ($models as $model) {
$query->orWhere(function (Builder $query) use ($model) {
// Add base constraints
$query->where($this->related->getTable() . '.' . $this->ownerKey, $model->getAttribute($this->foreignKey));
// Add extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$query->where($this->related->getTable() . '.' . $value, $model->getAttribute($key));
}
});
}
});
}
public function match(array $models, Collection $results, $relation)
{
$dictionary = [];
foreach ($results as $result) {
// Base constraints
$keys = [$result->getAttribute($this->ownerKey)];
// Extra constraints
foreach ($this->conditions as $key => $value) {
$keys[] = $result->getAttribute($value);
}
// Build nested dictionary
$current = &$dictionary;
foreach ($keys as $key) {
$current = &$current[$key];
}
$current = $result;
unset($current);
}
foreach ($models as $model) {
$current = $dictionary;
// Base constraints
if (!isset($current[$model->{$this->foreignKey}])) {
continue;
}
$current = $current[$model->{$this->foreignKey}];
// Extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
if (!isset($current[$model->{$key}])) {
continue 2;
}
$current = $current[$model->{$key}];
}
// Set passed result
$model->setRelation($relation, $current);
}
return $models;
}
}
HasExtendedRelationships.php
<?php
declare(strict_types=1);
namespace App\Database\Eloquent\Concerns;
use App\Database\Eloquent\Relations\BelongsToWith;
use Illuminate\Support\Str;
trait HasExtendedRelationships
{
public function belongsToWith(array $conditions, $related, $foreignKey = null, $ownerKey = null, $relation = null): BelongsToWith
{
if ($relation === null) {
$relation = $this->guessBelongsToRelation();
}
$instance = $this->newRelatedInstance($related);
if ($foreignKey === null) {
$foreignKey = Str::snake($relation) . '_' . $instance->getKeyName();
}
$ownerKey = $ownerKey ?: $instance->getKeyName();
return new BelongsToWith($conditions, $instance->newQuery(), $this, $foreignKey, $ownerKey, $relation);
}
}
Then:
class Post extends Base
{
use HasExtendedRelationships;
public function section(): BelongsToWith
{
return $this->belongsToWith(['website'], App\Models\Section::class, 'id_cat');
}
}
$posts = Post::with('section')->find([1, 2]);
Your Eager Loading query will be like:
select * from `sections`
where (
(
`sections`.`id` = {$posts[0]->id_cat}
and `sections`.`website` = {$posts[0]->website}
)
or
(
`sections`.`id` = {$posts[1]->id_cat}
and `sections`.`website` = {$posts[1]->website}
)
)

Codeigniter function_exists not working correctly

I am using php function_exists() function exist on my Welcome controller. But for some reason it keeps on throwing my show_error even though my slideshow function exists.
With in my foreach loop I get module function name from database which in the foreach loop is called $function = $module['code'];
Question is: How am I able to make sure function_exists checks
function exists correctly?
<?php
class Welcome extends CI_Controller {
public function index() {
$data['content_top'] = $this->content_top();
$this->load->view('home', $data);
}
public function content_top() {
$data['modules'] = array();
$modules = $this->get_module();
foreach ($modules as $module) {
$function = $module['code'];
if (function_exists($function)) {
$setting_info = array('test' => 'testing');
if ($setting_info) {
$data['modules'][] = $this->$function($setting_info);
}
} else {
show_error('This ' . $function . ' does not exist on ' . __CLASS__ . ' controller!');
}
}
return $this->load->view('content_top', $data, TRUE);
}
public function banner() {
}
public function slideshow($setting) {
$data['test'] = $setting['test'];
$this->load->view('module/slideshow', $data);
}
public function get_module() {
$query = $this->db->get('modules');
return $query->result_array();
}
}
function_exists() works on functions, but not class methods - these are different things. What you want is method_exists():
method_exists($this, $function);

select fails in custom model codeigniter 2

I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.

Joomla 2.5 pagination

I want to add pagination to my component, i've created a simple model with query. I must be missing something. What else do I need here ?
MODEL
jimport('joomla.application.component.modellist');
class PaieskaModelPradinis extends JModelList
{
public function getListQuery()
{
$db = JFactory::getDBO();
$query = "SELECT * FROM #__content";
$db->setQuery( $query );
$db->query( $query );
$result = $db->LoadObjectList();
return $result;
}
}
VIEW
jimport( 'joomla.application.component.view');
class PaieskaViewPradinis extends JView
{
protected $items;
protected $pagination;
function display ($tpl = null)
{
$this->items = $this->get('ListQuery');
$this->pagination = $this->get('Pagination');
parent::display($tpl);
}
}
TPL
foreach ($this->items as $item) {
echo $item->title;
}
EDITED:
I edited a bit code, so now it works fine, almost. Button display(number of rows to display) is not working. And I wonder if this part can be done in a different way ?
$limit = JRequest::getVar('limit' , 25);
$start = JRequest::getVar('start' , 0);
$query = "SELECT * FROM #__content LIMIT $start, $limit";
-
class PaieskaModelPradinis extends JModelList
{
public function getItems()
{
$db = JFactory::getDBO();
$limit = JRequest::getVar('limit' , 25);
$start = JRequest::getVar('start' , 0);
$query = "SELECT * FROM #__content LIMIT $start, $limit";
$db->setQuery( $query );
$db->query( $query );
$lists = $db->LoadObjectList();
return $lists;
}
function getPagination()
{
$main = JFactory::getApplication();
$db = JFactory::getDBO();
$limit = JRequest::getVar('limit' , 25);
$limitstart = JRequest::getVar('limitstart', 0);
$query = "SELECT count(title) FROM #__content";
$db->setQuery( $query );
$total = $db->loadResult();
// include a pagination library
jimport('joomla.html.pagination');
$pagination = new JPagination($total, $limitstart, $limit);
return $pagination;
}
}
VIEW
jimport( 'joomla.application.component.view');
class PaieskaViewPradinis extends JView
{
function display($tpl = null)
{
$this->items = $this->get('items');
$this->pagination = $this->get('pagination');
parent::display($tpl);
}
}
Going off your original code, not the edited version.
The getListQuery method only builds your database query, so you don't execute your query here. Use com_weblinks as an example for building out your model: https://github.com/joomla/joomla-cms/blob/2.5.x/components/com_weblinks/models/category.php
follow this link http://docs.joomla.org/J1.5:Using_JPagination_in_your_component properly.
I have used Joomla pagination. You'll be able to use Joomla pagination easily, if you follow documentation properly. BTW its very simple.

Resources