Get time difference in eloquent. Laravel - datetime

There's a table 'comment' with column time-stamp. I want the time difference from the date comment has been created to current date and time like created '5 Days ago' somewhat. I have no idea how to do that from eloquent.
My controller is:
public function show($id)
{
$vehicles=vehicles::findorfail($id);
$user=users::where('id',$vehicles->Users_id)->get()->first();
//adding view count
$viewad=ads::where('Vehicleid',$id)->get()->first();
$viewcount=$viewad->views;
$ad = ads::find($viewad->id);
$ad->views=$viewcount+1;
$ad->save();
$comments=comment::where('vehicles_id',$id)->get();
return view('Bike.show',compact('vehicles','user','viewcount','comments'));
}
How can i accomplish this task? Can anyone tell me how to do it?

If you want it available in the view the easiest way is to make an attribute accessor in the model.
First import Carbon at the start of the file use Carbon\Carbon;.
Then create the attribute accessor in your Comment model:
public function getTimeDifferenceAttribute()
{
return $this->time_stamp->diffForHumans(Carbon::now);
}
(I've used snake_case for the timestamp attribute name because the kebab-case version you used isn't valid in PHP variable names.)
Then it's available from a comment as $comment->time_difference.
EDIT:
This answer assumed that the model was treating time_stamp as a date. If this is not the case you should also add protected $dates = ['time_stamp']; to the model.

Use Carbon. See Carbon for the details.
$comments=comment::where('vehicles_id',$id)->get();
$today=Carbon::now();
and the view:
#foreach($comments as $comment)
{{$comment->name}} Created {{$today->diffForHumans($comment->time_stamp)}}
#endforeach
You have to import the namespace to use Carbon:
use Carbon\Carbon;

Related

Is it possible to override Symfony Intl JSON data?

Is it possible to override json data under symfony/src/Symfony/Component/Intl/Resources? For example, in data/languages/en.json I would like to change "zh": "Chinese" to be more specifically "zh": "Mandarin Chinese".
I'm not the pro with Symfony, but i get the same question and for me, i did find a workaround that works. I didn't use it in forms, i use it only to display.
I did create a Model called Country for accessing and manipulating the RegionBundle:
namespace AppBundle\Model;
use Symfony\Component\Intl\Data\Bundle\Reader\BufferedBundleReader;
use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReader;
use Symfony\Component\Intl\Data\Bundle\Reader\JsonBundleReader;
use Symfony\Component\Intl\Intl;
use Symfony\Component\Intl\ResourceBundle\RegionBundle;
class Country
{
public static function getCountryName($countryCode, $locale='de')
{
$test = new RegionBundle(
__DIR__.'/../Resources/Intl/data'.'/'.Intl::REGION_DIR,
new BundleEntryReader(new BufferedBundleReader(
new JsonBundleReader(),
Intl::BUFFER_SIZE
)),
Intl::getLocaleBundle()
);
return $test->getCountryName($countryCode, $locale);
}
}
And from a controller, i can call them with:
Country::getCountryName('AF')
Maybe this is not the "state of the art" approach, but i was spending hours of searching another solution - but dont find any approach that is useable for me.
Did you tried to copy that file under app/Resources/data/languages/en.json than change it over there?
Also don't forget to clear cache

Laravel : display personal format of timestamps fields

In my project I used this code to format timestamps fields
date('D m Y H:i', strtotime($post->created_at))
But as I have many places and fields to display it's a bit boring, and if I need to change the format it won"t be easy to maintain.
I'd like to know if there is a way to decalre the output format
You can create an accessor function in your Post model.
public function getCreatedAtAttribute($value)
{
return date('D m Y H:i', strtotime($value));
}
This way, each time you'll call $post->created_at it will display the date returned by your accessor instead of the default value.
More info here : http://laravel.com/docs/eloquent#accessors-and-mutators
If you don't want this function in all your models your can create a BaseModel class and make your models extend this BaseModel class.
I also found an other solution:
\Carbon\Carbon::setToStringFormat('D m Y H:i');
You can use this line (in global.php for exemple) but it will change the date format in all the application.

Does Grails have a built-in way to bind a string to a date for a single bean property?

I know that it's possible to register a custom property editor, as demonstrated here. It is my understanding that this will cause all properties for the registered type to be bound using that custom editor.
(Perhaps that's a misunderstanding on my part? If so, enlighten me!)
However, what if I only want to register a custom editor for a single property on a given domain?
Example:
class MyCommand {
Date foo // bind this using a custom format, e.g. 'yyyy-MM-dd'
Date bar // bind this using the normal 'struct' date picker fields
}
class MyController {
def myAction = { MyCommand command ->
// params has [foo: '2011-01-01', bar: 'struct', ...]
// which get bound to command as above
}
}
Does Grails have a built-in way to do this?
I know that it's possible to register a custom property editor, as demonstrated here. It is my understanding that this will cause all properties for the registered type to be bound using that custom editor.
AFAIK, this is correct
However, what if I only want to register a custom editor for a single property on a given domain?
If you're using Grails 2.3.0 or later, you can do this like so:
class MyCommand {
#BindingFormat('yyyy-MM-dd')
Date foo // bind this using a custom format, e.g. 'yyyy-MM-dd'
Date bar // bind this using the normal 'struct' date picker fields
}
You could write getter and setters that take the format you want and return the format you want. The DateFormatter or SimpleDateFormatter classes would be useful in your get/set methods.
You can still use the neat trick for dates in grails:
<g:form>
<g:hiddenField name="myDomainInstance.bar_year" value="2011"/>
<g:hiddenField name="myDomainInstance.bar_month" value="07"/>
<g:hiddenField name="myDomainInstance.bar_day" value="01"/>
<g:textField name="myDomainInstance.bar_hour" value=""/>
<g:textField name="myDomainInstance.bar_minute" value=""/>
</g:form>
In controller:
myDomainInstance.properties = params.myDomainInstance
Will result in the desired date for bar.

Can I create a column of nvarchar(MAX) using FluentMigrator?

Using FluentMigrator, the default creation of a Column using .AsString() results in an nvarchar(255). Is there a simple way (before I modify the FluentMigrator code) to create a column of type nvarchar(MAX)?
You could create an extension method to wrap .AsString(Int32.MaxValue) within .AsMaxString()
e.g.
internal static class MigratorExtensions
{
public static ICreateTableColumnOptionOrWithColumnSyntax AsMaxString(this ICreateTableColumnAsTypeSyntax createTableColumnAsTypeSyntax)
{
return createTableColumnAsTypeSyntax.AsString(int.MaxValue);
}
}
OK, I found it. Basically, use .AsString(Int32.MaxValue). Pity there's not a .AsMaxString() method, but I guess it's easy enough to put in...
You can use AsCustom("nvarchar(max)") and pack it to extension
If you often create columns/tables with the same settings or groups of columns, you should be creating extension methods for your migrations!
For example, nearly every one of my tables has CreatedAt and UpdatedAt DateTime columns, so I whipped up a little extension method so I can say:
Create.Table("Foos").
WithColumn("a").
WithTimestamps();
I think I created the Extension method properly ... I know it works, but FluentMigrator has a LOT of interfaces ... here it is:
public static class MigrationExtensions {
public static ICreateTableWithColumnSyntax WithTimestamps(this ICreateTableWithColumnSyntax root) {
return root.
WithColumn("CreatedAt").AsDateTime().NotNullable().
WithColumn("UpdatedAt").AsDateTime().NotNullable();
}
}
Similarly, nearly every one of my tables has an int primary key called 'Id', so I think I'm going to add Table.CreateWithId("Foos") to always add that Id for me. Not sure ... I actually just started using FluentMigrator today, but you should always be refactoring when possible!
NOTE: If you do make helper/extension methods for your migrations, you should never ever ever change what those methods do. If you do, someone could try running your migrations and things could explode because the helper methods you used to create Migration #1 works differently now than they did earlier.
Here is the code for creating columns incase it helps you create helper methods: https://github.com/schambers/fluentmigrator/blob/master/src/FluentMigrator/Builders/Create/Column/CreateColumnExpressionBuilder.cs
How about extending like this:
public static class StringMaxMigratorExtensions
{
public static ICreateTableColumnOptionOrWithColumnSyntax AsStringMax(this ICreateTableColumnAsTypeSyntax createTableColumnAsTypeSyntax)
{
return createTableColumnAsTypeSyntax.AsCustom("nvarchar(max)");
}
public static IAlterColumnOptionSyntax AsStringMax(this IAlterColumnAsTypeSyntax alterColumnAsTypeSyntax)
{
return alterColumnAsTypeSyntax.AsCustom("nvarchar(max)");
}
}

How can I identify an Axapta class Name from the class ID?

Please can someone help me make sense of the Batch madness?
I'm trying to debug an Axapta 3.0 implementation that has about 50 Batch Jobs. Most of the batched classes do not implement the description() method, so when you look at the Batch List form (Basic>>Inquiries>>Batch list) the description field is blank. You can see the Batch Group and the Start Time, etc. but you can't tell which class is actually being called.
The Batch table contains a hidden field called ClassNum which identifies the ID property of the class. Can anyone tell me how I can find the corresponding class from the ID? Once I've identified the culprits I can add descriptions.
I tried using the standard Find function on the AOT but it doesn't pick them up.
Any suggestions would be most welcome!
Many thanks,
Mike
Jay's answer provides two comprehensive solutions.
I've just discovered that the global class ClassId2Name does the same thing, so you can simply have:
display str Classname()
{
return ClassId2Name(this.ClassNum);
}
There atleast two ways to do this, you can use the DictClass class:
display ClassName className()
{
DictClass dictClass = new DictClass(this.ClassNum);
;
if(dictClass!=null)
return dictClass.name();
return '';
}
Or using the UtilIdElements table:
display ClassName className()
{
UtilIdElements utilIdElements;
;
select utilIdElements where utilIdElements.id==this.ClassNum && utilIdElements.recordType==UtilElementType::Class;
if(utilIdElements)
return utilIdElements.name;
return '';
}
Alternative to get ClassName if ClassNum is not available.
display str Classname()
{
return classId2Name(ClassIdGet(this));
}

Resources