Post::with('commentsCount')->get();
public function commentsCount()
{
return $this->comments()
->selectRaw('count(id) as aggregate')
->groupBy('id');
}
public function getCommentsCountAttribute()
{
if ( ! array_key_exists('commentsCount', $this->relations))
$this->load('commentsCount');
$related = $this->getRelation('commentsCount')->first();
return ($related) ? (int) $related->aggregate : 0;
}
public function boot()
{
Blade::directive('example', function ($expression) {
return "{$expression}";
});
}
{{ $page_title }} @example('toster.ru')
public function comments() {
return $this->hasMany('App\Comment')->selectRaw('id, name, SUBSTRING(comment, 30) as comment_limit')->orderBy('id', 'DESC');
}
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
site.ru/users?param=value
site.ru/users/{user}
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AjaxController extends Controller {
public function request(Request $request) {
if($request->ajax()){
$param = $request->input('param');
echo json_encode($param);
}
}
}
Route::post('ajax/request', 'AjaxController@request');
jQuery.ajax({
url: location.origin + '/ajax/request',
async: false,
type: 'POST',
data: {'param': '32'},
dataType: 'json',
success: function(data) {
alert(data);
},
error: function() {
alert('Ошибка');
}
});