Funny Frontend Funny Frontend - 10 months ago 339
PHP Question

Can't use Carbon Laravel method in my laravel .blade view

In my Controller I get the current date an another date, I send this params to my view.blade:

$current_date = Carbon::now('Europe/Madrid');
$second_date = Carbon::create(2016, 6, 3, 00, 00, 00, 'Europe/Madrid');


In my Controller this function works fine:

$current_date->lt($second_date) # true


But in my blade.php Laravel report this error:
FatalErrorException in efcb37f79f0e8cb86e0f747997c402d6f7026ada.php line 112:
Call to a member function lt() on string


I debug my laravel view and the lt() method receives a correct Carbon object

Carbon {#361 ▼
+"date": "2016-06-03 00:00:00.000000"
+"timezone_type": 3
+"timezone": "Europe/Madrid"
}


what is happening here?

My view code:

@foreach ($articles_rows as $articles_row)
@if($current_date->lt($articles_row['expiration_date']))
<div class="row">
...show articles here
</div>
@endif
@endforeach


My controller code:

$articles_rows = array (

array(
'img_src' => FuImg::asset('img/regalos-para-profesores.jpg'),
'img_alt' => 'Regalos para profesores',
'expiration_date' => Carbon::create(2016, 6, 3, 00, 00, 00, 'Europe/Madrid'),
'class' => 'teacher-gifts',
'articles' =>
# Articulos
FotiArticle::getList(array(
'fields' => 'article_id,name,group_id,group,price_pvp_currency,quantity,prices,stock_available',
'expand' => 'group,prices',
'article_id' => '2829,186,2875,1728',
'order' => 'PRICE',
)),

),

array(
'img_src' => Img::asset('img/regalos-ocasiones-especiales.jpg'),
'img_alt' => 'Ocasiones especiales',
'expiration_date' => Carbon::create(2016, 6, 2, 00, 00, 00, 'Europe/Madrid'),
'class' => 'wedding',

'articles' => Article::getList(array(
'fields' => 'article_id,name,group,price_pvp_currency,quantity,prices,stock_available',
'expand' => 'prices',
'article_id' => '1611,4481,50,5345',
'order' => 'PRICE',
)),
),

);

Answer

Issue over here is with the $articles_row['expiration_date'] which is considered as a string and not an object of Carbon class. So the work around over is, you need to create an object of Carbon class for your $articles_row['expiration_date'] using parse method like as

$current_date->lt(\Carbon\Carbon::parse($articles_row['expiration_date']))