Why can't if part not executed in laravel 5 controller method? - laravel-5

public function index1()
{
// $g = Request::input('grade');
//$s = Request::input('subject');
$g=$_POST['grade'];
$s=$_POST['subject'];
if(strcmp($g,'Select A Grade')==0 || strcmp($s,'Select A Subject')==0){
if(strcmp($s,'Select A Subject')!=0){
// Session::flash('msg', 'Please select the Subject.');
return redirect()->back()->withInput();
}
else if(strcmp($g,'Select A Grade')!=0){
// Session::flash('msg', 'Please select the Grade.');
return redirect()->back()->withInput();
}
}
else{
$u = DB::table('upldtbls')->where('grade',$g)->where('subject',$s)->get();
return view('2Eng',compact('u'));
}
}
Above is the controller method. Main else part executed correctly. But main if part not executed I guess. In main if condition I want to stay on the same page if drop box values are equal to that. Can any one figure out this mess?

I guess this is what you what to do:
if(strcmp($s,'Select A Subject') !== 0 ){
// Session::flash('msg', 'Please select the Subject.');
return redirect()->back()->withInput();
}
else if(strcmp($g,'Select A Grade') !== 0 ){
// Session::flash('msg', 'Please select the Grade.');
return redirect()->back()->withInput();
}
Ps.
Don't use $_POST, use this:
https://laravel.com/docs/5.2/requests
And for validation its more convenient to use:
https://laravel.com/docs/5.1/validation

Related

how to check count of likes and dislike for post for rating sysytem

i am making an system to check count of likes and dislike if like count is more then dislike count then it gives true
but i am getting an error
// if (Files::withCount('likes') >= Files::withCount('dislike')) {
// return response()->json(['true']);
// }elseif (Files::withCount('dislike') >= Files::withCount('like')) {
// return response()->json(['false']);
// }else{
// return response()->json(['error'=>'somethingwenrwrng']);
// }
// if( DB::table('files')->select('files_id')
// ->join('likes','files_id.files_id','=','files_id') > DB::table('files')->select('id')
// ->join('dislike','files_id.files_id','=','files_id') ){
// return response()->json(['true']);
// }else {
// return response()->json(['error'=>'somethingwenrwrng']);
// }
$file = Files::find($id);
if($file ->likes->count() > $file ->dislike->count() ){
return response()->json(['true']);
}else{
return response()->json(['error'=>'somethingwenrwrng']);
}
i have tried different method to check but getting an error
the withCount() method return a property of the related field_count counting related models
so
$file = Files::find($id)->withCount(['likes','dislikes']);
if($file->likes_count > $file->dislikes_count ){
return response()->json(['true']);
}

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

Laravel redirect inside of middleware?

I have a middleware check by login, how many games has the user, I want to show another view if user have more than one game, but I got everytime redirect error if user has more than one:
This is in case $assigned_games > 1
$games = Auth::user()->userGames;
$assigned_games = count($games);
if ($assigned_games == 1) {
return $next($request);
} elseif ($assigned_games > 1) {
return redirect()->route('games.board');
} elseif ($assigned_games < 1) {
echo "no game bought";
exit;
}
I tried also only with return route('games.board') but it don't work.
How can I set correct redirect here?
if both your route is inside middleware then you should check the current route and if its same as you are redirecting you shouldn't redirect to avoid redirect loop
$games = Auth::user()->userGames;
$assigned_games = count($games);
if ($assigned_games == 1) {
return $next($request);
} elseif ($assigned_games > 1 && \Route::currentRouteName() != 'games.board') {
return redirect()->route('games.board');
} elseif ($assigned_games < 1) {
echo "no game bought";
exit;
} else {
return $next($request);
}

Filtering Eloquent Collection

Trying to filter a collection object down based upon any combination of multiple values. This is as far as I've got. Not happening. Any clues for me?
public function search()
{
$posts = Posting::all();
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($country_id) && $country_id>0 )
{
return $post->where('country_id','=',$country_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($province_id) && $province_id>0 )
{
return $post->where('province_id','=',$province_id);
}
})->values();
return $posts;
}
Any help appreciated.
First off, you should really do a validation for the id being larger than 0, if they were provided. You shouldn't be manually checking that out.
But anyhow, why are you using filter, when you can just directly use Eloquent (I omitted the check for id being bigger than 0):
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$query = Posting::query();
if ( ! empty($type_id)) $query->whereTypeId($type_id);
if ( ! empty($country_id)) $query->whereCountryId($country_id);
if ( ! empty($province_id)) $query->whereProvinceId($province_id);
return $query->get();
First off, you need to return something that makes sense from the closure in your filter:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})
Above returns Eloquent\Builder object, which is evaluated to true, so.. it really doesn't make sense.
This is what you need:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->type_id == $type_id; // bool
}
})
With such code, you will filter the collection. $posts now will hold only those items, that match the statement in that closure.

Ignoring Codeigniter's _remap for certain URLs?

I use Codeigniter's _remap function to remap all urls to www.website.com. This works for 99% of cases, but I'd like it to ignore certain URLS (specifically /admin,/contact,/submit,/top,/browse). These URLs have content I'd like to display.
How would I achieve this?
public function _remap($urlname)
{
if($urlname == "index") {
// If this is the index, redirect to the most recent startup
redirect("s/".$this->Startup_model->getMostRecent(), 'refresh');
} else {
// If they didn't go to the index, find the startup they were after
$id = $this->Startup_model->matchName($urlname);
// Check to see if the name they entered was a real startup, if not redirect to missing page
if($id == null) {
$data['urlname'] = $urlname;
$this->load->view('header/header');
$this->load->view('content/missing', $data);
$this->load->view('footer/footer');
} else {
// They got the name right! Load the page...
$data['values'] = $this->Startup_model->buildStartup($id);
// If there was no next startup avaiable, pass that info through
$next = $this->Startup_model->findNext($id);
if($next == null) {
$next = '343z61v';
}
// If there was no previous startup avaiable, pass that info through
$previous = $this->Startup_model->findPrevious($id);
if($previous == null) {
$previous = '343z61v';
}
$data['next'] = $next;
$data['previous'] = $previous;
$this->load->view('header/header');
$this->load->view('content/startup', $data);
$this->load->view('footer/footer');
}
}
}
Try this:
function _remap($urlname, $params = array())
{
if(is_callable(array($this, $urlname))){ //If the function exists, is called, if not using the usual
return call_user_func_array(array(&$this, $urlname), $params);
}elseif($urlname == "index") {
// If this is the index, redirect to the most recent startup
redirect("s/".$this->Startup_model->getMostRecent(), 'refresh');
} else {
// If they didn't go to the index, find the startup they were after
$id = $this->Startup_model->matchName($urlname);
// Check to see if the name they entered was a real startup, if not redirect to missing page
if($id == null) {
$data['urlname'] = $urlname;
$this->load->view('header/header');
$this->load->view('content/missing', $data);
$this->load->view('footer/footer');
} else {
// They got the name right! Load the page...
$data['values'] = $this->Startup_model->buildStartup($id);
// If there was no next startup avaiable, pass that info through
$next = $this->Startup_model->findNext($id);
if($next == null) {
$next = '343z61v';
}
// If there was no previous startup avaiable, pass that info through
$previous = $this->Startup_model->findPrevious($id);
if($previous == null) {
$previous = '343z61v';
}
$data['next'] = $next;
$data['previous'] = $previous;
$this->load->view('header/header');
$this->load->view('content/startup', $data);
$this->load->view('footer/footer');
}
}
}
Note:
Function index() should not exist
So you're asking how to selectively not remap certain urls? If so, add this to your if statement before the else:
else if (in_array($urlname, array('admin', 'contact', 'etc')))
{
$this->$urlname;
}

Resources