What I Want to do
I want to convert URLs to tags like this:
あいうえおかきくけこhttp://localhostさしすせそたちつてと
↓
あいうえおかきくけこhttp://localhostさしすせそたちつてと
I want to use a custom Function in Model to do it.
What I did
I added this to my model:
class hogehoge extend Model {
public function convertUrlToLink($value)
{
// URLをaタグで囲む
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:#&=+$,%#]+)/';
$replace = '$1';
$text = preg_replace($pattern, $replace, $value);
return $text;
}
}
and called it like this:
Hogehoge::first(1)->text->convertUrlToLink()
But this gives an error:
Call to a member function convertUrlToLink() on string (View: /app/resources/views/club/show.blade.php)
How can I make custom Function in Model and use it in my templates?
You can access your attribute text directly in the model
class Hogehoge extend Model {
public function convertUrlToLink()
{
// URLをaタグで囲む
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:#&=+$,%#]+)/';
$replace = '$1';
$text = preg_replace($pattern, $replace, $this->text);
return $text;
}
}
Then you don't need it there
Hogehoge::first(1)->convertUrlToLink()
If it needs to be reusable, I would do a static method (that's only a preference)
public static function convertUrlToLink($value)
{
// URLをaタグで囲む
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:#&=+$,%#]+)/';
$replace = '$1';
$text = preg_replace($pattern, $replace, $value);
return $text;
}
Then you use it like this
Hogehoge::convertUrlToLink(Hogehoge::first(1)->text)
Hogehoge::convertUrlToLink(Hogehoge::first(1)->someAnotherText)
Related
Can anybody help as I am trying to use the codeigniter's upload library from the helpers folder but I keep getting the same error that I am not selecting an image to upload? Has any body tried this before?
class FileUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'file_uploading'));
$this->load->library('form_validation', 'upload');
}
public function index() {
$data = array('title' => 'File Upload');
$this->load->view('fileupload', $data);
}
public function doUpload() {
$submit = $this->input->post('submit');
if ( ! isset($submit)) {
echo "Form not submitted correctly";
} else { // Call the helper
if (isset($_FILES['image']['name'])) {
$result = doUpload($_FILES['image']);
if ($result) {
var_dump($result);
} else {
var_dump($result);
}
}
}
}
}
The Helper Function
<?php
function doUpload($param) {
$CI = &get_instance();
$CI->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|png|jpg|jpeg|png';
$config['file_name'] = date('YmdHms' . '_' . rand(1, 999999));
$CI->upload->initialize($config);
if ($CI->upload->do_upload($param['name'])) {
$uploaded = $CI->upload->data();
return $uploaded;
} else {
$uploaded = array('error' => $CI->upload->display_errors());
return $uploaded;
}
}
There are some minor mistakes in your code, please fix it as below,
$result = doUpload($_FILES['image']);
here you should pass the form field name, as per your code image is the name of file input.
so your code should be like
$result = doUpload('image');
then, inside the function doUpload you should update the code
from
$CI->upload->do_upload($param['name'])
to
$CI->upload->do_upload($param)
because Name of the form field should be pass to the do_upload function to make successful file upload.
NOTE
Make sure you added the enctype="multipart/form-data" in the form
element
I'm trying to understand Joomla language and I have this situation:
In a models/calcoloonline.php I have this function
public function estraivariabili()
{
$db = JFactory::getDBO();
// Put the result into a variable first, then return it.
$value = $db->setQuery("SELECT * FROM #__calcolo_imposte")->loadObjectList();
if ($value != NULL)
{
return $value;
}
else
{
return JFactory::getApplication()->enqueueMessage(JText::_('COM_CALCOLO_IMPOSTE_IMPORTI_NON_DEFINITI'), 'type');
}
}
This works perfectly but I'd like that after check if the return is NULL I want to hide display default.php and show only the message on JText.
How can I do this?
For your purpose, you just return the $value from the model function and call the function at view.html.php's display() function.
At default.php file check the availability of the $value and show your contents.
For example, you store the data at view.php.html. It looks like
public function display($tpl = null)
{
$model = $this->getModel();
$this->value = $model->estraivariabili();
return parent::display($tpl);
}
And your default.php file would be
<?php if (!empty($this->value)) { ?>
<h1>The value is not empty.</h1>
<?php } else {
// value not found :(
JFactory::getApplication()->enqueueMessage(JText::_('NOT_FOUND_MESSAGE'), 'warning');
} ?>
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}
)
)
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);
In CI, I have a model...
<?php
class User_crud extends CI_Model {
var $base_url;
var $category;
var $brand;
var $filter;
var $limit;
var $page_number;
public function __construct($category, $brand, $filter, $limit, $page_number) {
$this->base_url = base_url();
$this->category = $category;
$this->brand = $brand;
$this->filter = $filter;
$this->limit = $limit;
$this->page_number = $page_number;
}
public function get_categories() {
// output
$output = "";
// query
$this->db->select("name");
$this->db->from("categories");
$query = $this->db->get();
// zero
if ($query->num_rows() < 1) {
$output .= "No results found";
return $output;
}
// result
$output .= "<li><a class=\"name\">Categories</a></li>\n";
foreach ($query->result_array as $row) {
$output = "<li>{$row['name']}</li>\n";
}
return $output;
}
while I am calling this in my controller...
<?php
class Pages extends CI_Controller {
// home page
public function home() {
}
// products page
public function products($category = "cell phones", $brand = "all", $filter = "latest") {
// loading
$this->load->model("user_crud");
//
}
Now, How can I pass the $category, $brand and $filter variables to the user_crud model while loading/instantiation?
You shouldn't be using your model like this, just pass the items you need for the functions you require:
$this->load->model("user_crud");
$data['categories'] = $this->user_crud->get_categories($id, $category, $etc);
I would suggest (after seeing your code) that you study the fantastic codeigniter userguide as it has really good examples, and you just went a totally different way (treating model like an object). Its more simple sticking to how it was designed vs what you are doing.
You can not. A better idea would be to setup some setters in your model class along with some private vars and set them after loading the model.
if you return $this from the setters you can even chain them together like $this->your_model->set_var1('test')->set_var2('test2');