PHP / LARAVEL 5 ErrorException in MainController.php - 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 = "";
}

Related

Copying data between tables

I need to copy records from DeCategories to Categories (about 1.7 million) along with "processing" (new slug etc).
Category use: https://packagist.org/packages/kalnoy/nestedset
The following script works fine, but works for many days. How to optimize / make it work faster? I am beginner in Laravel.
I have this models
class DeCategories extends Model
{
use ScopeActiveTrait;
protected $quarded = ['id'];
protected $fillable = ['category_name', 'description', 'keywords', 'content', 'enable', 'photo', 'order', 'slug', '_lft', '_rgt', 'parent_id'];
public $timestamps = true;
protected $table = 'cms_multikategorie22';
}
class Category extends Model
{
use ScopeActiveTrait;
use NodeTrait;
use Slugable;
public function setCategoryNameAttribute($value)
{
$this->attributes['category_name'] = $value;
$this->attributes['slug'] = $this->makeSlug($value);
}
protected $quarded = ['id'];
protected $fillable = ['category_name', 'description', 'keywords', 'content', 'enable', 'photo', 'order', 'slug', '_lft', '_rgt', 'parent_id'];
public $timestamps = false;
}
trait Slugable
{
protected function makeSlug($value)
{
$slug = str_slug($value);
$count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? "{$slug}-{$count}" : $slug;
}
}
trait ScopeActiveTrait
{
public function scopeActive($query)
{
return $query->where('enable', 1);
}
}
And controller:
public function index()
{
echo 'Importuje <br/>';
//die();
$level1 = DeCategories::where('title', "<>", '')->where('parent_id', 325193)->get();
if (!$level1->isEmpty()) {
foreach ($level1 as $key1 => $value1) {
echo $value1->title . "<br/>";
////////
$slug = str_slug($value1->title);
$next = 1;
while (Category::where('slug', '=', $slug)->exists()) {
$next++;
$slug = str_slug($value1->title . '-' . $next);
}
////////
$category = new Category();
$category->category_name = $value1->title;
$category->description = $value1->title;
$category->keywords = $value1->title;
$category->content = $value1->id . '-1';
$category->enable = 1;
$category->photo = '';
$category->order = $value1->position;
$category->parent_id = 0;
$category->slug = $slug;
$category->save();
$id1 = $category->id;
$level2 = DeCategories::where('parent_id', $value1->id)->get();
//dump($level2);
if (!$level2->isEmpty()) {
foreach ($level2 as $key2 => $value2) {
////////
$slug2 = str_slug($value2->title);
$next2 = 1;
while (Category::where('slug', '=', $slug2)->exists()) {
$next2++;
$slug2 = str_slug($value2->title . '-' . $next2);
}
////////
$category2 = new Category();
$category2->category_name = $value2->title;
$category2->description = $value2->title;
$category2->keywords = $value2->title;
$category2->content = $value2->id . '-2';
$category2->enable = 1;
$category2->photo = '';
$category2->order = $value2->position;
$category2->parent_id = $id1;
$category2->slug = $slug2;
$category2->save();
$id2 = $category2->id;
$level3 = DeCategories::where('parent_id', $value2->id)->get();
if (!$level3->isEmpty() && $value2->id !="" && $value2->id != null) {
foreach ($level3 as $key3 => $value3) {
////////
$slug3 = str_slug($value3->title);
$next3 = 1;
while (Category::where('slug', '=', $slug3)->exists()) {
$next3++;
$slug3 = str_slug($value3->title . '-' . $next3);
}
////////
$category3 = new Category();
$category3->category_name = $value3->title;
$category3->description = $value3->title;
$category3->keywords = $value3->title;
$category3->content = $value3->id . '-3';
$category3->enable = 1;
$category3->photo = '';
$category3->order = $value3->position;
$category3->parent_id = $id2;
$category3->slug = $slug3;
$category3->save();
$id3 = $category3->id;
$level4 = DeCategories::where('parent_id', $value3->id)->get();
if (!$level4->isEmpty() && $value3->id !="" && $value3->id != null) {
foreach ($level4 as $key4 => $value4) {
////////
$slug4 = str_slug($value4->title);
$next4 = 1;
while (Category::where('slug', '=', $slug4)->exists()) {
$next4++;
$slug4 = str_slug($value4->title . '-' . $next4);
}
////////
$category4 = new Category();
$category4->category_name = $value4->title;
$category4->description = $value4->title;
$category4->keywords = $value4->title;
$category4->content = $value4->id . '-4';
$category4->enable = 1;
$category4->photo = '';
$category4->order = $value4->position;
$category4->parent_id = $id3;
$category4->slug = $slug4;
$category4->save();
$id4 = $category4->id;
$level5 = DeCategories::where('parent_id', $value4->id)->get();
if (!$level5->isEmpty() && $value4->id !="" && $value4->id != null) {
foreach ($level5 as $key5 => $value5) {
$slug5 = str_slug($value5->title);
$next5 = 1;
while (Category::where('slug', '=', $slug5)->exists()) {
$next5++;
$slug5 = str_slug($value5->title . '-' . $next5);
}
$category5 = new Category();
$category5->category_name = $value5->title;
$category5->description = $value5->title;
$category5->keywords = $value5->title;
$category5->content = $value5->id . '-5';
$category5->enable = 1;
$category5->photo = '';
$category5->order = $value5->position;
$category5->parent_id = $id4;
$category5->slug = $slug5;
$category5->save();
$id5 = $category5->id;
$level6 = DeCategories::where('parent_id', $value5->id)->get();
if (!$level6->isEmpty() && $value5->id !="" && $value5->id != null) {
foreach ($level6 as $key6 => $value6) {
$slug6 = str_slug($value6->title);
$next6 = 1;
while (Category::where('slug', '=', $slug6)->exists()) {
$next6++;
$slug6 = str_slug($value6->title . '-' . $next6);
}
$category6 = new Category();
$category6->category_name = $value6->title;
$category6->description = $value6->title;
$category6->keywords = $value6->title;
$category6->content = $value6->id . '-6';
$category6->enable = 1;
$category6->photo = '';
$category6->order = $value6->position;
$category6->parent_id = $id5;
$category6->slug = $slug6;
$category6->save();
$id6 = $category6->id;
$level7 = DeCategories::where('parent_id', $value6->id)->get();
if (!$level7->isEmpty() && $value6->id !="" && $value6->id != null) {
foreach ($level7 as $key7 => $value7) {
$slug7 = str_slug($value7->title);
$next7 = 1;
while (Category::where('slug', '=', $slug7)->exists()) {
$next7++;
$slug7 = str_slug($value7->title . '-' . $next7);
}
$category7 = new Category();
$category7->category_name = $value7->title;
$category7->description = $value7->title;
$category7->keywords = $value7->title;
$category7->content = $value7->id . '-7';
$category7->enable = 1;
$category7->photo = '';
$category7->order = $value7->position;
$category7->parent_id = $id6;
$category7->slug = $slug7;
$category7->save();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
echo 'finish';
}
For this quantity, IMO, you shouldn't use Models. They are heavy and this case it's taking huge time. Instead, use DB::table('x')->....
For dealing with the slug, I recommend the cviebrock/eloquent-sluggable. Give it a try ;)
You will see a tremendous reduce on execution time, just by doing that.

Writing a function in laravel

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) { ... }
}

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.

Unknown column in where clause in codeigniter query

I have a codeigniter project. I have some dropdowns where i can select campus, session, class, group. I want filter data according to these dropdown values. Here is the function i call-
function student_feeConfig()
{
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
$campus_id = -1;
$session_id = -1;
$class_id = -1;
$group_id = -1;
if($this->input->post('campus_id') !=null)
$campus_id = $this->input->post('campus_id');
if($this->input->post('session_id') !=null)
$session_id = $this->input->post('session_id');
if($this->input->post('class_id') !=null)
$class_id = $this->input->post('class_id');
if($this->input->post('group_id') !=null)
$group_id = $this->input->post('group_id');
if($this->input->post('section_id') !=null)
$section_id = $this->input->post('section_id');
$campus = $this->db->get('campus')->result_array();
$page_data['campus'] = array(''=>'Select one');
foreach($campus as $row):
$page_data['campus'][$row['id']] = $row['campus_name'];
endforeach;
$page_data['id'] = $campus_id;
$session = $this->db->get('session')->result_array();
$page_data['sessions'] = array(''=>'Select one');
foreach($session as $row):
$page_data['sessions'][$row['id']] = $row['uniqueCode'];
endforeach;
$page_data['session_id'] = $session_id;
$classinfo = $this->db->get_where('class', array('campus_id' => $campus_id))->result_array();
$page_data['classes'] = array(''=>'Select one');
foreach($classinfo as $row):
$page_data['classes'][$row['class_id']] = $row['name'];
endforeach;
$page_data['allclass']=$page_data['classes'];
$page_data['class_id'] = $class_id;
$groups = $this->db->get_where('class_group', array('class_id' => $class_id))->result_array();
$page_data['groups'] = array(''=>'Select one');
foreach($groups as $row):
$page_data['groups'][$row['id']] = $row['group_name'];
endforeach;
$page_data['group_id'] = $group_id;
if($class_id != -1) {
$this->db->select('enroll.group_id, student_feeConfig.*');
$this->db->from('enroll');
$this->db->join('student_feeConfig', 'enroll.student_id = student_feeConfig.student_id');
$this->db->where('enroll.class_id', $class_id);
$feeInfo = $this->db->get()->result_array();
$page_data['feeInfo'] = $feeInfo;
}
$page_data['page_name'] = 'student_feeconf';
$page_data['page_title'] = get_phrase('fee_management');
$this->load->view('backend/index', $page_data);
}
But i get error:
Error Number: 1054
Unknown column 'enroll.class_id' in 'where clause'
UPDATE `ci_sessions` SET `timestamp` = 1478060781 WHERE `enroll`.`class_id` = '4' AND `id` = 'a351278bf35ab714c6f3de3479627cb5c009c7a6'
Filename: libraries/Session/drivers/Session_database_driver.php
Line Number: 243
Your code is :
if($class_id != -1) {
$this->db->select('enroll.group_id, student_feeConfig.*');
$this->db->from('enroll');
$this->db->join('student_feeConfig', 'enroll.student_id = student_feeConfig.student_id');
$this->db->where('enroll.class_id', $class_id);
$feeInfo = $this->db->ge()->result_array();
$page_data['feeInfo'] = $feeInfo;
}
bellow line you used ->db->ge() like this
$feeInfo = $this->db->ge()->result_array();
Correction is bellow :
$feeInfo = $this->db->get()->result_array();
and add your enroll.class_id like bellow after if($class_id != -1) { condition:
$this->db->select('enroll.group_id, enroll.class_id, student_feeConfig.*');

Laravel : search or filter the collection

I have this issue while filtering or searching through a collection
http://laravel.io/bin/vj115 check the url for code.
What i am trying to do is filter a collection by get method (from url ofcourse)
But only it only works when Input::get('category') has value else nothing works.
Could you please check the code and let me know what need to be fixed?
Thanks.
===== Real Code just incase the link is broken in future (edited)=============
public function anyIndex() {
$id = Input::get('id');
$brand = Brand::firstOrNew(array('id' => $id));
$paginate = Misc::getSettings('admin-pagination');
$page_no = isset($_GET['page']) ? $_GET['page'] : 1;
$i = ($paginate * $page_no) - ($paginate - 1);
$appends = false;
$newBrands = new Brand;
if (Input::get('category')) {
$brandCat = BrandCategory::find(Input::get('category'));
$newBrands = $brandCat->brands();
$appends['category'] = Input::get('category');
}
if (Input::get('status')) {
$status = Input::get('status') == 'published' ? 1 : 0;
$newBrands->where('is_active', '=', $status);
$appends['status'] = Input::get('status');
}
if (Input::get('order_by') || Input::get('order')) {
if (Input::get('order_by')) {
$order_by = Input::get('order_by');
$appends['order_by'] = Input::get('order_by');
} else {
$order_by = 'name';
}
if (Input::get('order')) {
$order = Input::get('order');
$appends['order'] = Input::get('order');
} else {
$order = 'asc';
}
$order = Input::get('order') ? Input::get('order') : 'asc';
$newBrands->orderBy($order_by, $order);
}
$brands = $newBrands->paginate($paginate);
$brand_categories_list = new BrandCategory;
$selected_cats = array();
if ($id != "") {
$selected_cats = $brand->categories->lists('id');
}
return View::make('admin.brands.index')
->with(array(
'selected_cats' => $selected_cats,
'brand' => $brand,
'brands' => $brands,
'brand_categories_list' => $brand_categories_list->lists('name', 'id'),
'appends' => $appends,
'i' => $i
));
}
Thanks to Dave.. I solved it as :
public function anyIndex() {
$id = Input::get('id');
$brand = Brand::firstOrNew(array('id' => $id));
$paginate = Misc::getSettings('admin-pagination');
$page_no = isset($_GET['page']) ? $_GET['page'] : 1;
$i = ($paginate * $page_no) - ($paginate - 1);
$appends = false;
if (Input::has('category')) {
$brandCat = BrandCategory::find(Input::get('category'));
$newBrands = $brandCat->brands();
$appends['category'] = Input::get('category');
} else {
$newBrands = Brand::limit(-1);
}
if (Input::has('status')) {
$status = Input::get('status') == 'published' ? 1 : 0;
$newBrands->where('is_active', '=', $status);
$appends['status'] = Input::get('status');
}
if (Input::has('order_by') || Input::has('order')) {
if (Input::has('order_by')) {
$order_by = Input::get('order_by');
$appends['order_by'] = Input::get('order_by');
} else {
$order_by = 'name';
}
if (Input::has('order')) {
$order = Input::get('order');
$appends['order'] = Input::get('order');
} else {
$order = 'asc';
}
$order = Input::get('order') ? Input::get('order') : 'asc';
$newBrands->orderBy($order_by, $order);
}else{
$newBrands->orderBy('name', 'asc');
}
$brands = $newBrands->paginate($paginate);
/* $queries = DB::getQueryLog();
$last_query = end($queries);
dd($last_query); */
$brand_categories_list = new BrandCategory;
$selected_cats = array();
if ($id != "") {
$selected_cats = $brand->categories->lists('id');
}
return View::make('admin.brands.index')
->with(
array(
'selected_cats' => $selected_cats,
'brand' => $brand,
'brands' => $brands,
'brand_categories_list' => $brand_categories_list->lists('name', 'id'),
'appends' => $appends,
'i' => $i)
);
}
I suspect it has to do with how you are using Eloquent. You can't simply apply methods to the object if it was created using the "new" keyword.
$newBrands = new Brand;
// This won't work
$newBrands->where('is_active', '=', $status);
// This will work
$newBrands = $newBrands->where('is_active', '=', $status);
It will work if you create it statically along with a method.
$newBrands = Brand::limit(100);
// This will work
$newBrands->where('is_active', '=', $status);
Fluent (DB) works the same way.
$newBrands = DB::table('brands');
// This wil work
$newBrands->where('is_active', '=', $status);
here I am searching the username(s) based on the displayname or fullname or email. therefore, the $request->filled('name of your input') is the solution.
$usernames = (new User())->newQuery(); //where User is the model
if($request->filled('email')){
$usernames->orWhere('email',$request->email);
}
if($request->filled('full_name')){
$usernames->orWhere('full_name',$request->full_name);
} if($request->filled('display_name')){
$usernames->orWhere('display_name',$request->display_name);
}
$usernames = $usernames->pluck('username')->toArray();

Categories