Sunday, October 18, 2020

Laravel Dynamic caching for website speed!

 Route::get('/{slug}','SiteController@postDetails');

//Example URL: example.com/awesome-post-title public function postDetails($slug){ $post = Cache::remember('posts.'.$slug, function($slug) use($slug) { return Post::where('slug',$slug)->first(); }); return view('frontend.posts.post-details',['post'=>$post]); } To read more: https://bit.ly/speed-up-laravel-website

Laravel search query example

 return $query->when(!empty(request()->input('location', 0)), function($query) {

$query->whereHas('location', function($query) { $query->whereId(request()->input('location')); }); }) ->when(!empty(request()->input('category', 0)), function($query) { $query->whereHas('categories', function($query) { $query->whereId(request()->input('category')); }); }) ->when(!empty(request()->input('search', '')), function($query) { $query->where(function($query) { $search = request()->input('search'); $query->where('title', 'LIKE', "%$search%") ->orWhere('short_description', 'LIKE', "%$search%") ->orWhere('full_description', 'LIKE', "%$search%") ->orWhere('job_nature', 'LIKE', "%$search%") ->orWhere('requirements', 'LIKE', "%$search%") ->orWhere('address', 'LIKE', "%$search%") ->orWhereHas('company', function($query) use($search) { $query->where('name', 'LIKE', "%$search%"); }); }); });

Laravel custom helper

 

/**
* @return bool
*/
public function isLocalhost()
{
$list = array('127.0.0.1', '::1');
$host = $_SERVER['REMOTE_ADDR'];
if (in_array($host, $list) || strpos($host, '.test') !== false) {
// local
return true;
} else {
//production
return false;
}
}
/**************************
* Auth helpers
*************************/
/**
* @param null $guard
* @return bool
*/
public function isLoggedIn($guard = null)
{
return auth($guard)->check();
}
/**
* @param null $guard
* @return string|null
*/
public function getUsername($guard = null)
{
if (!auth($guard)->check()) return null;
return auth($guard)->user()->name;
}
/**
* @param null $guard
* @return int|null
*/
public function getUserId($guard = null)
{
if (!auth($guard)->check()) return null;
return auth($guard)->user()->id;
}
/**
* @param null $guard
* @return string|null
*/
public function getUserEmail($guard = null)
{
if (!auth($guard)->check()) return null;
return auth($guard)->user()->email;
}
/**
* @param null $guard
* @return object|null
*/
public function getCurrentUser($guard = null)
{
if (!auth($guard)->check()) return null;
return auth($guard)->user();
}
/***************************
* currency helper
***************************/
/**
* @param $amount
* @param int $decimal
* @return string
*/
public function toMoney($amount, $decimal = 2)
{
if (is_null($amount) || !is_numeric($amount)) return $amount;
return number_format($amount, $decimal);
}
/**
* @param $number
* @param array $option
* @return bool|mixed|string|null
*/ https://github.com/haruncpi/laravel-h/blob/master/src/H.php