Writing a function in laravel - php

I have the following function which fetch some data related to jobs from database. The user can search for jobs with job title / keyword, city and/or category. The user can either choose one option, e.g. searching jobs only by title, or by category. or he can use all options for deep search. Below is my function:
public function jobsearch(Request $request)
{
$keyword = htmlspecialchars($request->input('keyword'));
$city_id = $request->input('city_id');
$category_id = $request->input('category_id');
if($keyword !== '' && $city_id != 0 && $category_id == 0)
{
$data = DB::table('job_details')->where('job_title', 'like', '%'.$keyword.'%')->where('city_id', $city_id)->get();
}
elseif($keyword !== '' && $city_id == 0 && $category_id != 0)
{
$data = DB::table('job_details')->where('job_title', 'like', '%'.$keyword.'%')->where('category_id', $category_id)->get();
}
elseif($keyword == '' && $city_id != 0 && $category_id != 0)
{
$data = DB::table('job_details')->where('category_id', $category_id)->where('city_id', $city_id)->get();
}
elseif($keyword !== '' && $city_id == 0 && $category_id == 0)
{
$data = DB::table('job_details')->where('job_title', 'like', '%'.$keyword.'%')->get();
}
elseif($keyword == '' && $city_id == 0 && $category_id != 0)
{
$data = DB::table('job_details')->where('category_id', $category_id)->get();
}
elseif($keyword == '' && $city_id != 0 && $category_id == 0)
{
$data = DB::table('job_details')->where('city_id', $city_id)->get();
}
else
{
$data = DB::table('job_details')->where('job_title', 'like', '%'.$keyword.'%')->where('category_id', $category_id)->where('city_id', $city_id)->get();
}
foreach($data as $data)
{
echo $data->job_title.'<br>';
}
}
As you can see the function is too much messy with many if and elseif statements. My question is if there is any way to write the given function in clean way? How would you write the given function in your style? Please Help.

You're really missing out on the best parts of Laravel's query builder.
public function jobsearch(Request $request) {
// htmlspecialchars makes no sense here
$keyword = $request->input('keyword');
$city_id = $request->input('city_id');
$category_id = $request->input('category_id');
$query = DB::table('job_details');
if($keyword) {
$query->where('job_title', 'like', '%'.$keyword.'%');
}
if($city_id) {
$query->where('city_id', $city_id);
}
if($category_id) {
$query->where('category_id', $category_id);
}
$results = $query->get();
foreach($data as $data) { ... }
}

Related

PHP / LARAVEL 5 ErrorException in MainController.php

all.
I have problems after making some new steps. I'm rails developer, but now i have to do some support in php/laravel project. After making some UI + backend in project(adding OpenGraph in project + admin) - i made a command - php artisan migrate:fresh.
And now i have this code error.
(1/1) ErrorException
Trying to get property 'title' of non-object
in MainController.php line 78
MetaTag.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* App\Setting
*
* #mixin \Eloquent
*/
class MetaTag extends Model
{
/**
* #var array
*/
protected $table = "meta_tags";
protected $fillable = ['title', 'description', 'keywords','og_type','og_title','og_description'];
}
part of MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App\Http\Requests;
class MainController extends Controller
{
public function index()
{
$main_banner = \App\Banner::where('type', '1')
->where('page', '1')
->where('active', '1')
->orderBy('order', 'asc')
->first();
$premium_blocks = \App\Banner::where('type', '2')
->where('active', '1')
->orderBy('order', 'asc')
->get();
$active_animations = \App\Setting::where('alias', 'anumations_active')->first();
$active_films = \App\Setting::where('alias', 'films_active')->first();
$active_games = \App\Setting::where('alias', 'games_active')->first();
$active_heroes = \App\Setting::where('alias', 'heroes_active')->first();
$active_news = \App\Setting::where('alias', 'news_active')->first();
$active_soundtracks = \App\Setting::where('alias', 'soundtracks_active')->first();
$animations = \App\Animation::where('active', '1')
->orderBy('order', 'asc')
->get();
$films = \App\Film::where('active', '1')
->where('checked', '1')
->orderBy('order', 'asc')
->get();
$games = \App\Game::where('active', '1')
->where('checked', '1')
->orderBy('order', 'asc')
->get();
$heroes = \App\Hero::where('active', '1')
->where('checked', '1')
->orderBy('order', 'asc')
->get();
$news = \App\News::where('active', '1')
->where('checked', '1')
->orderBy('order', 'asc')
->get();
$soundtracks = \App\Soundtrack::where('active', '1')
->where('checked', '1')
->orderBy('order', 'asc')
->get();
$arr_month_rus = \Config::get('settings.arr_month_rus');
$arr_month_rus_lower = \Config::get('settings.arr_month_rus_lower');
$arr_games_types = \Config::get('settings.arr_games_types');
$arr_news_types = \Config::get('settings.arr_news_types');
$agent = new Agent();
$browser = $agent->browser();
$v = explode('.',$agent->version($agent->browser()));
$version = $v[0];
if (
($browser == "Internet Explorer" && $version > 10) ||
($browser == "Edge" && $version > 11) ||
($browser == "Firefox" && $version > 46) ||
($browser == "Opera" && $version > 38) ||
($browser == "Safari" && $version > 8) ||
($browser == "Chrome" && $version > 51)
)
$outdated = false;
else $outdated = true;
$meta_tags = \App\MetaTag::where('alias', '=', 'main_page')->first();
$title = $meta_tags->title;
$description = $meta_tags->description;
$keywords = $meta_tags->keywords;
$og_title = $meta_tags->og_title;
$og_description = $meta_tags->og_description;
$og_type = $meta_tags->og_type;
return view((($agent->isMobile()) ? 'mobile.home' : 'home'), compact(
'main_banner',
'premium_blocks',
'animations',
'films',
'games',
'heroes',
'news',
'soundtracks',
'active_animations',
'active_films',
'active_games',
'active_heroes',
'active_news',
'active_soundtracks',
'arr_games_types',
'arr_month_rus_lower',
'arr_news_types',
'arr_month_rus',
'outdated',
'title',
'description',
'keywords',
'og_title',
'og_type',
'og_description'
));
}
I expect just solve this little problem.
Thanks!
Check if this line returns anything:
$meta_tags = \App\MetaTag::where('alias', '=', 'main_page')->first();
You can add an if statement like this (but set a default value for the variables to prevent errors):
$meta_tags = \App\MetaTag::where('alias', 'main_page')->first(); // You CAN ignore the equal sign
if($meta_tags){
$title = $meta_tags->title;
$description = $meta_tags->description;
$keywords = $meta_tags->keywords;
$og_title = $meta_tags->og_title;
$og_description = $meta_tags->og_description;
$og_type = $meta_tags->og_type;
} else {
$title = "";
$description = "";
$keywords = "";
$og_title = "";
$og_description = "";
$og_type = "";
}
I think you should try this. the logic here is to check if the record exist in the database first.
$meta_tags_count = \App\MetaTag::where('alias', 'main_page')->count();
if($meta_tags_count>0){
$meta_tags = \App\MetaTag::where('alias', 'main_page')->first(); // You CAN ignore the equal sign
$title = $meta_tags->title;
$description = $meta_tags->description;
$keywords = $meta_tags->keywords;
$og_title = $meta_tags->og_title;
$og_description = $meta_tags->og_description;
$og_type = $meta_tags->og_type;
}
else {
$title = "";
$description = "";
$keywords = "";
$og_title = "";
$og_description = "";
$og_type = "";
}

Creating a new collection from another collection

im creating a collection of specific data from a query that i made, but i need to create a new collection with only some data with custom names properties, i was using arrays, but i need to make it in collections since is easyer to format the data and access some collections methods.
My current code is like:
$activity = [];
$temp = [];
$calculations = collect($user->calculations()
->withTrashed()
->orderBy('updated_at', 'desc')
->get());
foreach($calculations as $calculation){
$temp['type'] = "calculation";
$temp['name'] = $calculation->name;
$user = $this->getUserById($calculation->pivot->user_id);
$temp['user'] = $user->name ." ".$user->surname;
if($calculation->created_at == $calculation->updated_at && $calculation->deleted_at == null)
{
$temp['operation'] = "saved";
$temp['date'] = $calculation->created_at;
$temp['diff'] = Carbon::parse($calculation->created_at)->diffForHumans();
}elseif($calculation->created_at != $calculation->updated_at && $calculation->deleted_at != null)
{
$temp['operation'] = "changed";
$temp['date'] = $calculation->updated_at;
$temp['diff'] = Carbon::parse($calculation->updated_at)->diffForHumans();
}else{
$temp['operation'] = "delete";
$temp['date'] = $calculation->deleted_at;
$temp['diff'] = Carbon::parse($calculation->deleted_at)->diffForHumans();
}
array_push($activity,$temp);
}
$conditions = collect($user->conditions()
->withTrashed()
->orderBy('updated_at', 'desc')
->get());
foreach($conditions as $condition){
$temp['type'] = "condition";
$temp['name'] = $condition->name;
$user = $this->getUserById($condition->user_id);
$temp['user'] = $user->name ." ".$user->surname;
if($condition->created_at == $condition->updated_at && $condition->deleted_at == null)
{
$temp['operation'] = "saved";
$temp['date'] = $condition->created_at;
$temp['diff'] = Carbon::parse($condition->created_at)->diffForHumans();
}elseif($condition->created_at != $condition->updated_at && $condition->deleted_at != null)
{
$temp['operation'] = "alterado";
$temp['date'] = $condition->updated_at;
$temp['diff'] = Carbon::parse($condition->updated_at)->diffForHumans();
}else{
$temp['operation'] = "delete it";
$temp['date'] = $condition->deleted_at;
$temp['diff'] = Carbon::parse($condition->deleted_at)->diffForHumans();
}
array_push($activity,$temp);
I already convert the eloquent query to "collect", but how i cant createa new collections, i need to instead using the array methods, i should use the collection methods to create them.
Basically my main reason is that i need to merge the "conditions" and "calculations" for than be able to order the dataTime the collections.
How about something like this.
I've used transform method on collections (in order to transform the key names). I've replicated your logic and then merged both collections.
$calculations = $user->calculations()
->withTrashed()
->orderBy('updated_at', 'desc')
->get();
$transformed = $calculations->transform(function($item, $key) use($user) {
$toReturn = [];
$toReturn['type'] = "calculation";
$toReturn['name'] = $item->name;
$toReturn['user'] = $user->name;
if($item->created_at == $item->updated_at && $item->deleted_at == null) {
$toReturn['operation'] = "saved";
$toReturn['date'] = $item->created_at;
$toReturn['diff'] = Carbon::parse($item->created_at)->diffForHumans();
} elseif($item->created_at != $item->updated_at && $item->deleted_at != null){
$toReturn['operation'] = "changed";
$toReturn['date'] = $item->updated_at;
$toReturn['diff'] = Carbon::parse($item->updated_at)->diffForHumans();
} else {
$toReturn['operation'] = "delete";
$toReturn['date'] = $item->deleted_at;
$toReturn['diff'] = Carbon::parse($item->deleted_at)->diffForHumans();
}
return $toReturn;
});
$conditions = $user->conditions()
->withTrashed()
->orderBy('updated_at', 'desc')
->get();
$transformed2 = $conditions->transform(function($item, $key) use($user) {
$toReturn = [];
$toReturn['type'] = "calculation";
$toReturn['name'] = $item->name;
$toReturn['user'] = $this->getUserById($item->user_id);
if($item->created_at == $item->updated_at && $item->deleted_at == null) {
$toReturn['operation'] = "saved";
$toReturn['date'] = $item->created_at;
$toReturn['diff'] = Carbon::parse($item->created_at)->diffForHumans();
} elseif($condition->created_at != $condition->updated_at && $condition->deleted_at != null){
$toReturn['operation'] = "changed";
$toReturn['date'] = $item->updated_at;
$toReturn['diff'] = Carbon::parse($item->updated_at)->diffForHumans();
} else {
$toReturn['operation'] = "delete";
$toReturn['date'] = $item->deleted_at;
$toReturn['diff'] = Carbon::parse($item->deleted_at)->diffForHumans();
}
return $toReturn
});
$merged = $transform->merge($transform2);
Building on #devk 's answer here is a neater version without so much repetitive code:
/**
* Transform a collction with a given callback
*
* #param Collection $collection A laravel collection
* #param User $user A User object
* #return Collection
**/
private function transformCollection(Collect $collection, User $user) {
return $collection->transform(function($item, $key) use ($user) {
$toReturn = [
'type' => 'calculation',
'name' => $item->name,
'user' => $user->name
];
if ($item->created_at == $item->updated_at && $item->deleted_at == null) {
$toReturn['operation'] = "saved";
$toReturn['date'] = $item->created_at;
$toReturn['diff'] = Carbon::parse($item->created_at)->diffForHumans();
} elseif ($item->created_at != $item->updated_at && $item->deleted_at != null) {
$toReturn['operation'] = "changed";
$toReturn['date'] = $item->updated_at;
$toReturn['diff'] = Carbon::parse($item->updated_at)->diffForHumans();
} else {
$toReturn['operation'] = "delete";
$toReturn['date'] = $item->deleted_at;
$toReturn['diff'] = Carbon::parse($item->deleted_at)->diffForHumans();
}
return $toReturn;
});
}
// Return all user calculations ordered by when they were updated including deleted
$calculations = $user->calculations()->withTrashed()->orderBy('updated_at', 'desc')->get();
$conditions = $user->conditions()->withTrashed()->orderBy('updated_at', 'desc')->get();
// Transform both collections
$transformed = transformCollection($calculations, $user);
$transformed2 = transformCollection($conditions, $user);
// Merge the resulting collections into a single collection
$merged = $transform->merge($transform2);
Edit
If your Calculation object has a model you can also make sure that the dates are returned as Carbon dates by adding them to the protected $dates = [] array
protected $dates = [
'deleted_at',
'created_at',
'updated_at'
];
I think that created_at and updated_at are included in this by default as part of BaseModel, thought i could well be wrong.

How I can use strpos in search by foreach in array

The problem lies in the fact that I have to type the full name for the search phrase.
Maybe can I use strpos in this?
if ($filter && $searchOption && $searchPhrase && $sortField == "createDate" && $order == "asc") {
usort($caseList, function ($a, $b) {
/* #var $a CMCase */
/* #var $b CMCase */
$time1 = strtotime($a->createDate);
$time2 = strtotime($b->createDate);
return $time1 > $time2;
});
} else if ($filter && $searchOption == "search_customer" && $searchPhrase && $sortField && $order) {
$list = $caseList;
$caseList = array();
foreach ($list as $case) {
if ($case->customerName == $searchPhrase) {
$caseList[] = $case;
}
}
}
You can rewrite your code like this:
$result = array_filter($caseList, function($case) use ($searchPhrase){
return stripos($case->customerName, $searchPhrase) !== FALSE;
})
But you still need to be more concrete.
! I used stripos to case insensitive search. See the manual
P.S. Just try this instead of your code:
if ($searchOption == "search_customer" && $searchPhrase) use ($searchPhrase) {
$list = array_filter($caseList,function($case) {
return stripos($case->customerName, $searchPhrase) !== false;
});
}
This is my solution:
// Searching
{
if ($filter && $searchOption == "search_customer" && $searchPhrase && $sortField && $order) {
$list = array();
foreach ($caseList as $case) {
if (stripos($case->customerName,$searchPhrase)!== FALSE) {
$list[] = $case;
}
}
$caseList = $list;
} else if ($filter && $searchOption == "search_request" && $searchPhrase && $sortField && $order) {
$list = array();
foreach ($caseList as $case) {
if (stripos($case->identifier,$searchPhrase)!== FALSE) {
$list[] = $case;
}
}
$caseList = $list;
}
}

get() returns empty rows in Codeigniter

I am using the function below but it did not return any rows. I tried to do $query->num_rows() but it has null values. I got the last query using $this->db->last_query(), used this in the database and there are results. Am I missing a setup in Code Igniter? Looking forward to your reply.
function search($conditions=NULL,$tablename="",$orderby='id', $order='DESC',$limit=1000000,$offset=0)
{
if($tablename=="")
{
$tablename = $this->table;
}
if($conditions != NULL)
$this->db->where($conditions);
if ( $orderby !== "" and $order !== "")
$this->db->order_by($orderby, $order);
$query = $this->db->get($tablename,$limit,$offset=0);
return $query->result_array();
}
Try like
if($conditions != NULL)
$this->db->where($conditions);
if ( $orderby !== "" and $order !== "")
$this->db->order_by($orderby, $order);
$this->db->limit($limit,$offset);
$query = $this->db->get($tablename);
first you check $tablename is table name or blank
function search($conditions=NULL,$tablename="",$orderby='id', $order='DESC',$limit=1000000,$offset=0)
{
if($tablename=="")
{
$tablename = $this->table;
}
if($conditions != NULL)
$this->db->where($conditions);
if ( $orderby !== "id" and $order !== "DESC")
$this->db->order_by($orderby, $order);
$this->db->limit($limit);
$this->db->offset ($offset );
$query = $this->db->get($tablename);
if($query->num_rows() == 0){
}

php if statement null and 0?

i'm having trouble executing my if statement
if($parent == $page->parent)
my dollar $parent = null and my $page->parent = 0 how do i fix this that they are equal?
i think it's a problem with the fact it doesn't know that null is equal to 0
$page = Page::find($id);
$parent = Input::get('parent'); // Null
i hope you guys can help me out i have to figure this out
here's my controller just in case you wan't to take a look at it
public function updateMenu($id)
{
$page = Page::find($id);
$parent = Input::get('parent');
$new_order = Input::get('index');
if($parent == $page->parent)
{
if($page->order_id > $new_order)
{
DB::table('pages')
->where('parent',$parent)
->where('order_id', '<', $page->order_id)
->increment('order_id');
}
else
{
DB::table('pages')
->where('parent',$parent)
->where('order_id', '>=', $page->order_id)
->decrement('order_id');
}
}
else
{
DB::table('pages')
->where('parent',$parent)
->where('order_id', '>=', $new_order)
->increment('order_id');
}
$page->order_id = Input::get('index');
$page->parent = Input::get('parent');
$page->save();
return $id;
}
I dont think 0 can be equals with NULL. maybe if($parent == $page->parent || ($parent == null && $page->parent == 0)) more helpful
Use the strict equality operator: === instead of ==
localhost> = 0 === null
false
localhost> = 0 == null
true
You can use:
if(is_null($parent) && ($page->parent==0))
{
}

Categories