I have several fields in a form with dates and times ('dd-mm-yyyy', 'hh:mm').
When I want to save the form I use my own function to convert it for MySQL ('yyyy-mm-dd', 'H:i:s') via date() which I added to save() in Laravel Model Class.
But where is single place where I can put the same function to format output (SELECT queries)?
There is no single function in Laravel for data output. find(), findOrNew(), findOrFail(), ... - there are in different classes so I cant use single place to add the formatting function.
Is there any proper place to put formatting function?
You can use Laravel Date Mutator. Just put the following method in your Eloquent Model:
Suppose your have a table user in your database with expireDate column. then define this field in your model.
class User extends Eloquent {
protected $dates = ['expireDate'];
}
Just Replace FirstName with your database column name.
Then you can use laravel Carbon class to format your result.
$user = User::find(1);
return $user->expireDate->format('d-m-Y');
For more reference please read the http://laravel.com/docs/4.2/eloquent#date-mutators
Just add this to AppServiceProvider#register:
Carbon::setToStringFormat('d/m/y');
Now you can just echo $model->created_at and everything’s formatted correctly.
In App directory, create a new directory. Let call it "libraries",
then create a php file "CustomFunction.php" or whatever, this has to be a class as well, then put your function in this class.
So you have
class CustomFunction{
static function dateFormat(){
}
}
in App/libraries/
Then in App/start/global.php
Iside classloader on line 14, as below, add the path to your new folder:
ClassLoader::addDirectories(array(
app_path().'/libraries'
));
Then in your composer.json file, add:
"app/libraries" to "autoload" array.
Then in your view you can easily do this:
{{ CustomFunction::dateFormat() }}
Related
I was not happy with the default created_at date format in my database table so I decided to create Accessors which will simply change my date format. But I found out that Accessors is not running. I tried to use it on another column but it doesn't change my output. then I use dd($value) so it can stop in accessor but I found out that it didn't. I am getting my data from the database and the accessor is been bypassed.
my accessor in model class is:
public function getCreatedAtAttribute($value)
{
dd($value);
}
But it does not effect anything as I am getting my output of :
$case=Allcase::with('donner')->get();
print_r($case);
and also no effect to created_at:
You can customize the actual attribute value in this way
public function getCreatedAtAttribute()
{
return Carbon::parse($this->attributes['created_at'])->format('Y-m-d');
}
Now, you can get your data and print it. You can show the differences now
$case = Allcase::with('donner')->get();
print_r($case);
In my Laravel blade template, I have a table in which I want to add another column
after this code
<td>{{format_price($mission->amount)}}</td>
I added this :
#php
$amount_to_be_collected = DB::table('shipments')
->select('amount_to_be_collected')
->where('mission_id', $mission->id)
->get();
#endphp
<td>{{format_price($amount_to_be_collected)}}</td>
What is wrong with this code?
First of all, You should not put DB query code in your blade.
Now, when you run a query using eloquent and call get(), the response is a Collection::class instance that can be treated as an array but cannot be automatically transformed into a number/string.
If you only need the value of on field for one entry, use value() instead.
$amount_to_be_collected = DB::table('shipments')
->where('mission_id', $mission->id)
->value('amount_to_be_collected');
Note: It is not good to use db queries in blade views, you can also use helper
Try this before using DB facade you need to call this class in blade view Running Database Queries
use Illuminate\Support\Facades\DB;
I have a tables which I want to use one or more methods to all result from db. This method can change #hashtags to links, bbcode to html tags, etc. Let's assume that I have this query:
$query = Comments::orderBy('created_at', 'desc')->get();
Comments table has a comment column where user can use emoticons bbcode, etc. This query returns a few of results. How I can use method on column? If I have one result is simple:
$query = Posts::find(1);
$desc = myMethod($query->desc);
I assumne you want to format your eloquent attributes? have a look at https://laravel.com/docs/5.8/eloquent-mutators
and if you don't want to save your formatted data on db. you can just use the Accessor by defining it. for example please see below
// on your model you just need to create new methods
// with `get` as prefix and `Attribute` as suffix
public function getBbcToHtmlAttribute() {
return myMethod($query->desc);
}
please note that get and Attribute on your method name is required (e.g getMyNewAccessorAttribute`
after that you need to add casts property. if you already have casts property you just add it to the array if you dont have casts property you need to define it.
protected $casts = [
'BbcToHtml'
];
and then you can use it anywhere on your model instance.
$query = Posts::find(1);
$desc = $query->bbctohtml;
As MarkB has said, you would need to use a mutator, create a helper class that can take any input and produce the correct html code for your bbcode. Then you would create a mutator on your model and use that instead of the field where the bbcode text is.
What i am trying to achieve is in my database i have a table named channel
i am using laravel's eloquent class to access these the properties from the table
The problem that i am facing is that
the table name is column and the column name is channel
so when accessing that property looks like this.
User::find(1)->channel->channel
How can i modify this to say
User::find(1)->channel->name
We cannot change the table name in the database.
Options i have thought of:
1)Create views for tables that need columns changed. Too messy...
2)Use column alias.... laravel documentation...sigh.. no clue how?
3)Use a property set with the create_function that would call this->channel
but i am pretty sure it won't work because laravel is using dynamic properties. and when it's fill out in the array im pretty sure it changes it to the name of the column.
I could in my belongs_to/hasOne/hasMany function change the property to the alias of the name i want to use so that later on i can change it. i dunno how well that would work..
any thoughts?
much appreciated
You could probably do it easily with Accessors / Mutators.
class Channel extends Eloquent {
public function getNameAttribute()
{
return $this->attributes['channel'];
}
public function setNameAttribute($value)
{
$this->attributes['channel'] = $value;
}
}
Reference
Laravel Accessors & Mutators
I am working with Yii and I have the following situation:
I have a MySQL table:
charges {
id INT AUTOINCREMENT,
name VARCHAR(256),
value DOUBLE
}
Then I have the model from this table. And finally I have the views for create, list, admin, update and view.
In the admin and view views I want to display the value field formated with two decimal numbers. One option to do this could be in the view and admin files format the number. Is there a way to create a method in the model and then not having to do anything in the views but the method itself will solve formating the number?
thanks
You can override the afterFind() method of CActiveRecord in your model and format the value field in it.
Alternatively you could also declare a virtual attribute of the model, and set it in the afterFind() method, and use this virtual attribute in the views.
Example(with virtual attribute):
Class ChargesModel extends CActiveRecord{
public $valueModified;
/*
* other code
*/
protected function afterFind(){
parent::afterFind();
// in the following line i'm just making $valueModified and $value equal, but obviously you would have to insert the 2 decimals
$this->valueModified=$this->value;
}
}
Then you can access the virtual attribute like this : $modelObject->valueModified
I would recommend you to use the virtual attribute, because you then have both the unmodified $value and modified $modifiedValue, once the formatting is done, we can use either as required, and not have to reformat back to original when we need the original.