Best place for additional functions in Laravel 5 - laravel

I would like to know what is the best place to put additional functions in order to use it in a controller. Here is an example:
public function store(CreateServiceRequest $request)
{
function getMonth($value)
{
if ($value == 1)
{
return 1;
} else
if ($value == 2)
{
return 3;
} else
if ($value == 3)
{
return 6;
} else
return 0;
}
function getYear($value)
{
if ($value == 4)
{
return 1;
} else
if ($value == 5)
{
return 2;
} else
if ($value == 6)
{
return 3;
} else
return 0;
}
function getTax($price, $vat)
{
$tax = ($vat/100*$price);
return $tax;
}
$input = Request::all();
$months = getMonth($input['period']);
$years = getYear($input['period']);
$tax = getTax($input['price_net'], $input['vat']);
$input['price_vat'] = $tax;
$input['price_gross'] = $input['price_net'] + $tax;
$input['period_end'] = Carbon::createFromFormat('Y-m-d', $input['period_start'])->addYears($years)->addMonths($months)->toDateString();
return $input;
}
As you can see inside the store method I wrote three functions:
getMonth, getYear and getTax. The method first fetch all request, then I need to create some new variables - for instance I get the $input['period'] and use it to make $input['period_end']. So I don't change $input['period'] value but create a new $input['period_end']. If I would only change existing variable I used mutator... So the question is where I should put the code of getMonth, getYear and getTax functions? It seems like a mess in store method...

make helpers.php (in root, where .env file is).
if (! function_exists('helper_function')) {
function helper_function()
{
return 'hello';
}
}
and in your composer.json autoload it:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": [
"helpers.php"
]
},
now you are able to call your helper function everywhere in code base

Related

If clauses between where composition to laravel collect

Situation:
$post_1 = 'john';
$post_2 = 30;
$arr = array(['name'=>'john','number'=>70],['name'=>'clark','number'=>50]);
$collection = collect($arr);
if($post_1 == 'john')
{
$collection->where('name',$post_1);
}
if($post_2 == 70)
{
$collection->where('number',$post_2);
}
var_dump($collection->all());
But this doesn't work. I want to include filters but it depends on the post parameters to exist.
I think you can use when
$result= $collection->when(($post_1=="john"), function ($collection)use($post_1) {
return $collection->where('name',$post_1);
})->when(($post_2 == 70), function ($collection)use($post_2) {
return $collection->where('number',$post_2);
})->all();
dd($result);
or
$collection->when(($post_1=="john"), function ($collection)use($post_1) {
return $collection->where('name',$post_1);
})->when(($post_2 == 70), function ($collection)use($post_2) {
return $collection->where('number',$post_2);
});
dd($collection->all());
Ref:https://laravel.com/docs/8.x/collections#method-when

How to get all routes within a route group?

I need to print a main menu and instead of having a database where the links/ routes are stored I thought it there would be a way to get all routes that are in a named group, but all I find is getting routes by action.
web.php
Route::group(['as' => 'main'], function () {
Route::get('/', function () {
return view('pages.start');
})->name('Home');
Route::get('/foobar', function () {
return view('pages.foobar');
})->name('Home');
Route::get('/business', function () {
return view('pages.business');
})->name('Business');
});
I was looking for something like:
$routes = getRoutesByGroup('main');
I cannot really believe that a function like that doesnt exist in current Laravel but I cant seem to find this. What am I missing?
Maybe this can solve partially in your case
function getRoutesByStarting($start = '')
{
$list = \Route::getRoutes()->getRoutesByName();
if (empty($start)) {
return $list;
}
$routes = [];
foreach ($list as $name => $route) {
if (\Illuminate\Support\Str::startsWith($name, $start)) {
$routes[$name] = $route;
}
}
return $routes;
}
usage
getRoutesByStarting('main')
More general solution
function getRoutesByGroup(array $group = [])
{
$list = \Route::getRoutes()->getRoutes();
if (empty($group)) {
return $list;
}
$routes = [];
foreach ($list as $route) {
$action = $route->getAction();
foreach ($group as $key => $value) {
if (empty($action[$key])) {
continue;
}
$actionValues = Arr::wrap($action[$key]);
$values = Arr::wrap($value);
foreach ($values as $single) {
foreach ($actionValues as $actionValue) {
if (Str::is($single, $actionValue)) {
$routes[] = $route;
} elseif($actionValue == $single) {
$routes[] = $route;
}
}
}
}
}
return $routes;
}
usage
getRoutesByGroup(['middleware' => 'api']);
getRoutesByGroup(['middleware' => ['api']]);
getRoutesByGroup(['as' => 'api']);
getRoutesByGroup(['as' => 'api*']);
getRoutesByGroup(['as' => ['api*', 'main']]);
$allRoutes = Route::getRoutes()->getRoutes(); // fetch all rotues as array
$name = 'main'; // specify your full route name
$grouped_routes = array_filter($allRoutes, function($route) use ($name) {
$action = $route->getAction(); // getting route action
if (isset($action['as'])) {
if (is_array($action['as'])) {
return in_array($name, $action['as']);
} else {
return $action['as'] == $name;
}
}
return false;
});
// output of route objects in the 'main' group
dd($grouped_routes);

How to differentiate the multiple panels with login and session?

It create the session but does not go to index2 and index3 always redirect with else and go to index method but i want to go index2 and index3 to handle other panels also.
Session is created successfully for all just comming else condition all the time.
My form data and array is also showing when i using the print_r for my code to view if the data is comming or not.
Problem is it is showing no any error just redirect with file of index method.
My Controller
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Main_Model');
$this->load->helper('url');
$this->load->library('session');
$method = $this->router->fetch_method();
$methods = array('index','index2','index3');
if(in_array($method,$methods))
{
if(!$this->session->has_userdata('signup_email'))
{
redirect(base_url('Main/login'));
}
}
}
public function index()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('BKO/index');
}
}
public function index2()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('Admin/index');
}
}
public function index3()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('Owner/index');
}
}
public function login()
{
//$data['select'] = $this->Main_Model->get_select();
$this->load->view('login');
}
public function login_process()
{
//$roll = $this->input->post('select');
echo $email = $this->input->post('email');
echo $pass = $this->input->post('upass');
$query = $this->Main_Model->login_process($email,$pass);
if($query == TRUE)
{
$this->session->set_userdata('signup_email');
$session = array(
'signup_email' => $email
);
$this->session->set_userdata($session);
redirect(base_url('Main/check_login'));
}
else
{
$this->session->set_flashdata('error','Invalid Email or Password');
redirect(base_url('Main/login'));
}
}
public function check_login()
{
if($this->session->userdata() == 'admin#gmail.com')
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index2'));
}
elseif($this->session->userdata() == 'owner#gmail.com')
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index3'));
}
else
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index'));
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url());
}
My Model
public function login_process($email,$pass)
{
//$this->db->select('*');
//$this->db->where('roll_id',$roll);
$this->db->where('signup_email',$email);
$this->db->where('signup_password',$pass);
$query = $this->db->get('signup');
if($query->num_rows() > 0)
{
$this->session->set_flashdata('signup_email');
return true;
}
else
{
return false;
}
}
You missed the parameter here
if($this->session->userdata() == 'admin#gmail.com')
instead it should be
if($this->session->userdata('signup_email') == 'admin#gmail.com')

Fatal error: Call to a member function num_rows() on boolean in Code igniter

I have face this Fatal error: problem in local.
$rr = $this->CI->db->query("select * from $table $condition ");
$mm = $rr->num_rows();
if ($mm>0) {
return 1;
} else {
return 0;
}
<?php
$this->db->select("your stuff");
$query = $this->db->get("your table");
if($query->num_rows() > 0 ) {
return 1;
}
else {
return 0;
}
?>
$this->CI->db->query("select * from $table $condition ");
remove CI and
$this->db->query("select * from $table $condition ");
First have you autoload the database
$autoload['libraries'] = array('database');
If a your trying to load a library then use the $CI instance http://www.codeigniter.com/user_guide/general/ancillary_classes.html#get-instance
application > libraries > Example.php
<?php
class Example {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function somename() {
$query = $this->CI->db->query("select * from $table $condition ");
if ($query->num_rows() > 0) {
return 1; // return true;
} else {
return 0; // return false;
}
}
}
If on models
application > models > Example_model.php
<?php
class Example_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function somename() {
$query = $this->db->query("select * from $table $condition ");
if ($query->num_rows() > 0) {
return 1; // return true;
} else {
return 0; // return false;
}
}
}
Update one CI core file and resolve your error:
Go to : System/database/ and edit DB_active_rec.php file
Go to line no 990 and see blow code
if ($query->num_rows() == 0)
{
return 0;
}
Update to
if (!$query || $query->num_rows() == 0)
{
return 0;
}
Hope resolved your num_rows() issue.
class Site_m extends MY_Model {
protected $_table_name = 'setting';
protected $_primary_key = 'option';
protected $_primary_filter = 'intval';
protected $_order_by = "option asc";
function __construct() {
parent::__construct();
}
function get_site($id) {
$compress = array();
$query = $this->db->get('setting');
foreach ($query->result() as $row) {
$compress[$row->fieldoption] = $row->value;//here I am getting error
}
return (object) $compress;
}
}
/* End of file site_m.php */
This is fix in core CI-2
File
\system\database\DB_driver.php
Line in code
https://github.com/bcit-ci/CodeIgniter/blob/develop/system/database/DB_driver.php#L659
replace FALSE before end code
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
return FALSE;
}
To
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
$CR = new CI_DB_result();
return $CR;
}
Default should be return object empty
$CR = new CI_DB_result();
return $CR;

How to load models in the extended MY_Router class in codeigniter

I am not able to load models to the extended My_Router class in codeigniter. Below is my code:
class MY_Router extends CI_Router {
function MY_Router()
{
parent::CI_Router();
}
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Let's check if there are category segments
$category_routes = $this->category_routing($segments);
if($category_routes !== FALSE)
{
return $category_routes;
}
$user_routes = $this->user_routing($segments);
if($user_routes != FALSE)
{
return $user_routes;
}
show_404($segments[0]);
}
function category_routing($segments)
{
$this->load->model('category_model');
if($this->category_model->category_exist($segments[0]))
{
//if only category
if(count($segments)==1)
{
return array('category', 'category_browse', $segments[0]);
}
//category pagination
if(count($segments)==2 and is_numeric($segments[1]))
{
return array('category','category_browse', $segments[0], $segments[1]);
}
//category upcoming
if(count($segments)==2 and $segments[1] == 'upcoming')
{
return array('category','upcoming', $segments[0]);
}
//category upcoming pagination
if(count($segments)==3 and $segments[1] == 'upcoming' and is_numeric($segments[3]))
{
return array('category','upcoming', $segments[0], $segments[3]);
}
//category top
if(count($segments)==3 and $segments[1] == 'top')
{
return array('category','top', $segments[0], $segments[2]);
}
//category top pagination
if(count($segments)==4 and $segments[1] == 'top' and is_numeric($segments[3]))
{
return array('category','top', $segments[0], $segments[3]);
}
}
return FALSE;
}
function user_routing($segments)
{
$this->load->model('dx_auth/users', 'user_model');
if($this->user_model->check_username($segments[0]))
{
//only profile
if(count($segments)==1)
{
return array('user','profile',$segments[0]);
}
//all friends
if(count($segments)==2 and $segment[1]=='allfriends')
{
return array('user','allfriends',$segments[0]);
}
//all subscribers
if(count($segments)==2 and $segment[1]=='allsubscribers')
{
return array('user','allsubscribers',$segments[0]);
}
//all subscription
if(count($segments)==2 and $segment[1]=='allsubscriptions')
{
return array('user','allsubscriptions',$segments[0]);
}
}
return FALSE;
}
}
I have tried loading the models by using get_instance function provided by codeigniter but seems like it doesnot work. All i need is load the models in extended system library.
There is no access to the CodeIgniter super-global until CI_Base has been called which is extended by Controller. The Controller class then loads the Loader library:
// In PHP 5 the Loader class is run as a discreet
// class. In PHP 4 it extends the Controller
if (floor(phpversion()) >= 5)
{
$this->load =& load_class('Loader');
$this->load->_ci_autoloader();
}
The Router is loaded very on (have a look in system/codeigniter/CodeIgniter.php to see exactly when, on line 99) so has barely anything available.
You can use load_class('Whatever'); to load classes in a different order, but this can really screw with things if you are not careful, and you still wont have access to the database drivers.
Basically, you can't do it this way. You would need to try and directly work with the database library or use native MySQL bindings to access your data.
Here is what i did and it worked..Thanks phil for suggestion.
class MY_Router extends CI_Router {
function MY_Router()
{
parent::CI_Router();
}
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Let's check if there are category segments
$category_routes = $this->category_routing($segments);
if($category_routes !== FALSE)
{
return $category_routes;
}
$user_routes = $this->user_routing($segments);
if($user_routes !== FALSE)
{
return $user_routes;
}
show_404($segments[0]);
}
function category_routing($segments)
{
if($this->check_category_exist($segments[0]))
{
//if only category
if(count($segments)==1)
{
return array('category', 'category_browse', $segments[0]);
}
//category pagination
if(count($segments)==2 and is_numeric($segments[1]))
{
return array('category','category_browse', $segments[0], $segments[1]);
}
//category upcoming
if(count($segments)==2 and $segments[1] == 'upcoming')
{
return array('category','upcoming', $segments[0]);
}
//category upcoming pagination
if(count($segments)==3 and $segments[1] == 'upcoming' and is_numeric($segments[3]))
{
return array('category','upcoming', $segments[0], $segments[3]);
}
//category top
if(count($segments)==3 and $segments[1] == 'top')
{
return array('category','top', $segments[0], $segments[2]);
}
//category top pagination
if(count($segments)==4 and $segments[1] == 'top' and is_numeric($segments[3]))
{
return array('category','top', $segments[0], $segments[3]);
}
}
return FALSE;
}
function check_category_exist($cat_name)
{
//connect to database and find the category
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
mysql_select_db($db['default']['database'],$conn);
$sql = sprintf("SELECT COUNT(id) as count FROM categories WHERE permalink = '%s'", mysql_real_escape_string($cat_name));
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
mysql_close($conn);
if($row->count)
{
return TRUE;
}
return FALSE;
}
function user_routing($segments)
{
if($this->check_username_exist($segments[0]))
{
//only profile
if(count($segments)==1)
{
return array('user','profile',$segments[0]);
}
//all friends
if(count($segments)==2 and $segments[1]=='allfriends')
{
return array('user','allfriends',$segments[0]);
}
//all subscribers
if(count($segments)==2 and $segments[1]=='allsubscribers')
{
return array('user','allsubscribers',$segments[0]);
}
//all subscription
if(count($segments)==2 and $segments[1]=='allsubscriptions')
{
return array('user','allsubscriptions',$segments[0]);
}
}
return FALSE;
}
function check_username_exist($username)
{
//connect to database and find the category
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
mysql_select_db($db['default']['database'],$conn);
$sql = sprintf("SELECT COUNT(id) as count FROM users WHERE username = '%s'", mysql_real_escape_string($username));
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
mysql_close($conn);
if($row->count)
{
return TRUE;
}
return FALSE;
}
}
The following code will solve your problem too and will make your coding lot easier and flexible.
require_once( BASEPATH . 'database/DB' . EXT );
$db = & DB();
$query = $db->query("select ...");
$results = $query->result();
When using the base CodeIgniter class in external Libraries you have to invoke it again like this:
// load it
$CI =& get_instance();
$CI->load->model('model_name');
//use it
$CI->model_name->method()
Hope that helps

Resources