Passing data to your Javascript in Laravel

Today I'd like to share a library written by Jeffrey Way of Laracasts that has proven very useful in our latest client project in tidying up the DOM. For element based objects, it is usually easy to just stick values in data attributes so that you can pluck them out using JS.

<div class="rating" data-id="5" data-name="Doing It" data-rating="4">
    ...
</div>

<script>
	$('.rating').each(function(index, value) {
		var name = $(value).data('name');
		var rating = $(value).data('rating');
		
		// Do stuff
	});
</script>

With the descriptivley named "PHP-Vars-To-Js-Transformer" library, we can easily pass our data to JS without the need to scan the DOM.

public function posts()
{
	// Compile an array of objects to give to JS
	$toJs['ratings'] = [
		['id' => 5, 'name' => 'Doing It', 'rating' => 4],
		['id' => 6, 'name' => 'Netsells', 'rating' => 2],
	];
		
	JavaScript::put($toJs);
		
	return View::make('ratings.index');
}

// and in your js file (I've set our namespace to Netsells in config.php)
for (var i in Netsells.ratings) {
	console.log (Netsells.ratings[i].name + "'s rating is " + Netsells.ratings[i].rating);
}

Using this method, we can easily interact with data from our controller/models/services without having to mess up the DOM.

When dealing with Eloquent models, I like to pass through a presenter to only pass what I need rather than the entire Eloquent object. Something like:

function presentForJs($ratings)
{
	$return = [];
	
	foreach($ratings as $rating) {
		$return[] = [
			'name' => $rating->name,
			'rating' => $rating->rating,
		];
	}
	
	return $return;
}

There's quite a bit more I could have covered but I'll come back to this in a few weeks to let you know if we've found any other useful ways to use this library!