Reputation: 1578
I have 2 models Tour.php
and Itinerary.php
in one to many relations:
Tour.php
public function itinerary()
{
return $this->hasMany('App\Itinerary', 'tour_id')->orderBy('day', 'asc');
}
Itinerary.php
public function tour()
{
return $this->belongsTo('App\Tour', 'tour_id');
}
The itineraries
table consists of the following columns:
id |tour_id | day | detail
The day
& detail
column are of string type.
I want to print the itineraries of a tour according to ascending order of days.
How do I change the string to integer ?
I'm printing the output with foreach loop in the view:
@foreach($tour->itineraries as $item)
{{$item->day}}
{{$item->detail}}
@endforeach
I've tried cast method in model:
protected $casts = [
'day' => 'integer',
];
And Accessor
public function castDayToInt($value)
{
return (int)$value;
}
but didn't get the expected result.
Current output of the above code:
Expected output
Upvotes: 0
Views: 1099
Reputation: 13404
The best solution is change your day type in DB,
If you still need the varchar type, you can do it like this:
public function itineraries()
{
return $this->hasMany('App\Itinerary', 'tour_id')->orderByRaw('CONVERT(day, UNSIGNED) ASC');
}
Upvotes: 1