How to use DB:: from helper class - laravel

I have a helper class name common.php in App\Helpers folder. I want to use DB:: facade here to use some db table. In helper method My code is -
<?php
use DB;
function ref_number()
{
$last_row = DB::table('model_table')->latest('id')->first();
if($last_row) {
$ref = explode('-', $last_row->ref);
if($ref[0] === date('y')) {
// if running year
$ref = $ref[1] + 1;
$ref = date('y') .'-'. $ref;
}
else{
$ref = date('y') .'-'. 1; // if new year
}
}
else{
$ref = date('y') .'-'. 1; // if first data
}
return $ref;
}
But this not working. Following error has been arrived.
So how can i solve this?

Change your using to: Illuminate\Support\Facades\DB;

Related

How to add custom methods to Laravel Carbon

I've been searching this problem for 2 days but no luck. I want to add custom methods to laravel carbon. I use the syntax below:
namespace App\Http\Controllers\Helpers;
use Carbon\CarbonInterface;
interface CarbonJalaliInterface extends CarbonInterface {
public function toJalaliDateTimeString($unitPrecision = 'second');
public function toJalaliDateString($unitPrecision = 'second');
}
abstract class CarbonJalali implements CarbonJalaliInterface {
public function toJalaliDateTimeString($unitPrecision = 'second') {
list($part1, $part2) = explode(' ', $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)));
list($year, $month, $day) = explode('-', $part1);
list($hour, $minute, $second) = explode(':', $part2);
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
include_once ('jdf.php');
$jalali_date = jdate("H:i:s - Y/m/d",$timestamp);
return $jalali_date;
}
public function toJalaliDateString($unitPrecision = 'second') {
$timezone = 0;
list($part1, $part2) = explode(' ', $this->rawFormat('Y-m-d'));
list($year, $month, $day) = explode('-', $part1);
$timestamp = mktime($month, $day, $year);
include_once ('jdf.php');
$jalali_date = jdate("Y/m/d",$timestamp);
return $jalali_date;
}
}
But i get the error:
Symfony\Component\Debug\Exception\FatalErrorException DateTimeInterface can't be implemented by user classes
I want to use it like this :
CarbonJalali::now()->toJalaliDateTimeString();
Any suggestions? Thanks.

ErrorException in AssetController.php line 21: Trying to get property of non-object

I have this code source that i'm trying to use in one of my projects, it worked with laravel 5.2. This the function in the assetController:
namespace App\Http\Controllers;
use App\Setting;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AssetController extends Controller
{
/**
* List all image from image directory
*/
public function getAsset()
{
//Get Admin Images
$adminImages = array();
//get image file array
$images_dir = Setting::where('name', 'images_dir')->first();
$folderContentAdmin = File::files($images_dir->value);
//check the allowed file extension and make the allowed file array
$allowedExt = Setting::where('name', 'images_allowedExtensions')->first();
$temp = explode('|', $allowedExt->value);
foreach ($folderContentAdmin as $key => $item)
{
if( ! is_array($item))
{
//check the file extension
$ext = pathinfo($item, PATHINFO_EXTENSION);
//prep allowed extensions array
if (in_array($ext, $temp))
{
array_push($adminImages, $item);
}
}
}
//Get User Images
$userImages = array();
$userID = Auth::user()->id;
$images_uploadDir = Setting::where('name', 'images_uploadDir')->first();
if (is_dir( $images_uploadDir->value . "/" .$userID ))
{
$folderContentUser = File::files($images_uploadDir->value . "/" .$userID );
if ($folderContentUser)
{
foreach ($folderContentUser as $key => $item)
{
if ( ! is_array($item))
{
//check the file extension
$ext = pathinfo($item, PATHINFO_EXTENSION);
//prep allowed extensions array
//$temp = explode("|", $this->config->item('images_allowedExtensions'));
if (in_array($ext, $temp))
{
array_push($userImages, $item);
}
}
}
}
}
//var_dump($folderContent);
//var_dump($adminImages);
return view('assets/images', compact('adminImages', 'userImages'));
}
The problem is in the line 21 :
//get image file array
$images_dir = Setting::where('name', 'images_dir')->first();
$folderContentAdmin = File::files($images_dir->value);
From my research I find out that the reason is because the setting table is empty which it is true.
Please tell me if there is another cause to that problem if it's not the case I need a solution because I don't have a way to fill that table except doing it from the database itself (phpmyAdmin)

joomla - router change url when getting the name of product

I have build my own component in joomla and client wants now a friendly urls f.e
website.com/someplace/{product-id}-{product-name}. So i Build my own router like this.
function componentBuildRoute(&$query)
{
$segments = [];
if (isset($query['view'])) {
$segments[] = "szkolenie";
unset($query['view']);
}
if (isset($query['product_id'])) {
$productName = JFilterOutput::stringURLSafe(strtolower(getProductName($query['product_id'])));
$newName = $query['product_id'] . '-' . $productName;
$segments[] = $newName;
unset($query['product_id']);
}
return $segments;
}
and parse route function
function componentParseRoute($segments)
{
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item =& $menu->getActive();
$count = count($segments);
switch ($item->query['view']) {
case 'catalogue' : {
$view = 'training';
$id = $segments[1];
}
break;
}
$data = [
'view' => $view,
'product_id' => $id
];
return $data;
}
While on the end of buildroute function segments are ok I have exactly what I want that on the beginning of parse route I have something like
website.com/szkolenie/1-krakow <-- I dont know wtf is this krakow( I know it is city i Poland) but still where is it get from ? The getProductName function implementation is
function getProductName($productId)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('#__component_training.id as id, #__component_product' . name)
->from($db->quoteName('#__component_training'))
->where('#__s4edu_product.product_id = ' . $productId)
->leftJoin('#__component_product ON
#__component_training.product_id=#__component_product.product_id');
$training = $db->loadObject();
return trim($training->name);
}
So taking all this into consideration I think that something is happening between the buildRoute and parseRoute, something what filters the $segment[1] variable, but how to disable that and why is it happening ?
P.S
Please do not send me to https://docs.joomla.org/Joomla_Routes_%26_SEF
I already know all the tutorials on joomla website which contains anything with sef.
P.S.S
It is built on joomla 3.7.0
You do not have a product named "krakow" ?
If not you can try to remove the $productName from the build function, just to check if this "krakow" is added automaticaly or it's from the getProductName() function.
Also i noticed that you have an error i guess in the function getProductName()
->where('#__s4edu_product.product_id = ' . $productId)
It's should be
->where('#__component_product.product_id = ' . $productId)

Codeigniter function_exists not working correctly

I am using php function_exists() function exist on my Welcome controller. But for some reason it keeps on throwing my show_error even though my slideshow function exists.
With in my foreach loop I get module function name from database which in the foreach loop is called $function = $module['code'];
Question is: How am I able to make sure function_exists checks
function exists correctly?
<?php
class Welcome extends CI_Controller {
public function index() {
$data['content_top'] = $this->content_top();
$this->load->view('home', $data);
}
public function content_top() {
$data['modules'] = array();
$modules = $this->get_module();
foreach ($modules as $module) {
$function = $module['code'];
if (function_exists($function)) {
$setting_info = array('test' => 'testing');
if ($setting_info) {
$data['modules'][] = $this->$function($setting_info);
}
} else {
show_error('This ' . $function . ' does not exist on ' . __CLASS__ . ' controller!');
}
}
return $this->load->view('content_top', $data, TRUE);
}
public function banner() {
}
public function slideshow($setting) {
$data['test'] = $setting['test'];
$this->load->view('module/slideshow', $data);
}
public function get_module() {
$query = $this->db->get('modules');
return $query->result_array();
}
}
function_exists() works on functions, but not class methods - these are different things. What you want is method_exists():
method_exists($this, $function);

Laravel Passing Variable from a controller to another Controller

I'm trying to pass a variable from a controller to another controller I tried using
Redirect::to('dashboard/'.$ssid.'/')->with(compact('wname'))
but does not work any idea how can I achieve this?
here is my code
Route
Route::get('dashboard/{ssid}/', 'HomeController#showDash');
LoginController
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value):
$activated = $value['a_status'];
$wname = $value['wholename'];
endforeach;
if($activated == 1):
$red= Redirect::to('dashboard/'.$ssid.'/')->with(compact('wholename'));
else:
$red= View::make('login');
endif;
return $red;
}
}
HomeController
public function showDash($ssid,$wholename)
{
foreach ($wholename as $userVal):
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
endforeach;
return View::make('dashboard')->with(compact('fn'));
}
The error I'm having is that Missing argument 2 for HomeController::showDash() as per laravel's debugger..
Updated answer based on the comments:
public function post_index()
{
if(Auth::attempt($credentials)){
$users = User::where('username','=',$email)->get();
foreach ($users as $value){
$activated = $value['a_status'];
$wname = $value['wholename'];
}
if($activated == 1) {
Redirect::to('dashboard/'.$ssid.'/')->with(['wholename' => $wholename]);
}
return View::make('login');
}
public function showDash($ssid)
{
$wholename = (Session::has('wholename')) ? Session::get('wholename') : [];
foreach ($wholename as $userVal) {
$fn = $userVal['firstname'];
$ln = $userVal['lastname'];
}
return View::make('dashboard')->with(compact('fn'));
}
Everything else can stay as is.
Update: fixed erroneous space in 'whole name' (autocorrect did that, sorry).

Resources