I have payroll PayrollProcessController and PayrollHelper class in my Helpers folder.
here's my PayrollProcessController code :
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Base\MasterController;
use App\Http\Requests;
use App\Models\PayrollPeriod;
use App\Helpers\PayrollHelper;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Yajra\Datatables\Datatables;
class PayrollProcessController extends MasterController
{
protected $indexView = 'payroll_process.index';
protected $detailView = 'payroll_process.detail';
protected $routeBindModel = 'payroll_process';
protected $redirectPageWhenFormSuccess = 'payroll_process.index'; //Route Name
protected $title = 'Payroll Process';
public function render(View $view, $route = null, $obj = null, $method = 'POST')
{
$payrollPeriodName = PayrollPeriod::pluck('name','id');
$view->with(compact('payrollPeriodName'));
return parent::render($view, $route, $obj, $method);
}
}
and here's my PayrollHelper Code :
<?php
namespace App\Helpers;
use App\Helpers\Exceptions\ValidationException;
use App\Helpers\GeneralHelper;
use App\Models\Config;
use App\Models\Driver;
use App\Models\DriverPayable;
use App\Models\PayrollPeriod;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Log;
final class PayrollHelper {
public static function processPayroll(PayrollPeriod $payrollPeriod)
{
try {
$drivers = Driver::where('active', true)->get();
foreach ($drivers as $driver) {
$payable = new DriverPayable;
$payable->payrollPeriod()->associate($payrollPeriod);
$payable->driver()->associate($driver);
if (!$payable->save()) {
throw new ValidationException($payable->errors());
}
}
} catch (Exception $e) {
Log::error($e);
SessionHelper::setMessage('Unable to process payroll, Please contact system Administrator');
} catch (ValidationException $e) {
Log::info($e->errors);
SessionHelper::setMessage($e->errors);
}
}
}
?>
how to call the processPayroll function ?
Any help will be appreciated
Try this..
Use helper in your controller
use App\Helpers\PayrollHelper;
This is your controller constructor
public function __construct(PayrollHelper $payroll_helper)
{
parent::__construct();
$this->payroll_helper = $payroll_helper;
}
Call method like this
$this->payroll_helper->processPayroll();
Updated
Your controller look like this
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Base\MasterController;
use App\Http\Requests;
use App\Models\PayrollPeriod;
use App\Helpers\PayrollHelper;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Yajra\Datatables\Datatables;
class PayrollProcessController extends MasterController
{
protected $indexView = 'payroll_process.index';
protected $detailView = 'payroll_process.detail';
protected $routeBindModel = 'payroll_process';
protected $redirectPageWhenFormSuccess = 'payroll_process.index'; //Route Name
protected $title = 'Payroll Process';
public function __construct(PayrollHelper $payroll_helper)
{
parent::__construct();
$this->payroll_helper = $payroll_helper;
}
public function render(View $view, $route = null, $obj = null, $method = 'POST')
{
$payrollPeriodName = PayrollPeriod::pluck('name','id');
$view->with(compact('payrollPeriodName'));
//Use where you want
$this->payroll_helper->processPayroll();
return parent::render($view, $route, $obj, $method);
}
}
I just want to share what I have done,
Don't know yet the side effects of this but we'll,
Use helper in your controller
use App\Helpers\PayrollHelper;
And inside the function that is good to consume one of the functions inside Payroll helper, do
$payrollhelper = new PayrollHelper();
Then call any function within the helper doing
$payrollhelper->funtion_name()...
This worked for me
Here is the example how you can apply your class in that way
Import the controller class
use App\Http\Controllers\CategoryController;
Create an instance of this class
$category_instance = new CategoryController();
Call the method
$category_instance->convert_json_serial_numbers_to_arrays($serial_number);
Related
I'm trying to, from my controller, access a method in a model that is in another namespace and the only way I could do this was to make the method static. Is this the right way to do it, or is there any neater approach?
PagesController.php (controller):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\ConnectedHost;
class PagesController extends Controller
{
/*
* REMOVED CODE HERE FOR READABILITY
* Below is where I instantiate the "connectedHost"-object
*/
$hosts[$hostKey] = new ConnectedHost($hostAttributes['ipv4'], $hostAttributes['mac']);
}
/* REMOVED CODE HERE FOR READABILITY AS WELL */
ConnectedHost.php (helper-file):
namespace App\Helpers;
class ConnectedHost
{
public $ipv4, $mac;
public function __construct($ipv4, $mac)
{
$this->ipv4 = $ipv4;
$this->mac = $mac;
// This is where I call the getName-function staticly,
$this->name = \App\Host::getName();
}
}
Host.php (model):
namespace App;
use Illuminate\Database\Eloquent\Model;
class Host extends Model
{
// The method below is declared static
public static function getName()
{
$name = 'wenzzzel';
return $name;
}
}
If you are directly accessing the method from model like
$data = \App\ModelName::methodName();
Then your method should be static.
if your method is not static you can access like,
$model = new \App\ModelName();
$data = $model->methodName();
I would like to use a method from a class that I have in one trait. The class that I need looks like this:
namespace App\Http\Controllers;
use App\Libraries\Content\ContentInterface;
use Illuminate\Http\Request;
use App\Http\Requests;
use Corcel\Post;
use EllipseSynergie\ApiResponse\Laravel\Response;
use App\Transformers\IndexTransformer;
class ImportController extends Controller
{
private $indexable;
function __construct(Response $response, ContentInterface $contentInterface)
{
$this->indexable = \Config::get('middleton.wp.content.indexable_types');
$this->response = $response;
$this->contentInterface = $contentInterface;
}
public function updateOrCreateInventory($remoteId)
{
$this->contentInterface->updateOrCreateInventory($remoteId);
}
}
I would like to use the updateOrCreateInventory method in a trait that I have or to be more specific in it's method :
namespace App\Libraries\Content;
use App\Inventory;
use GuzzleHttp\Client;
use App\Http\Controllers\ImportController;
trait SupplementaryFormatter
{
private static function getInventoryUrl($id)
{
if (is_numeric($id)) {
$inventory = Inventory::where('remote_id', $id)->first();
if(!$inventory) {
ImportController::updateOrCreateInventory($id);
} else {
return '/' . $inventory->url;
}
}
return $id;
}
}
But, I am not sure how can I initiate the class in the trait with it's dependencies, because when I import the Response and ContentInterface class to a trait and try to pass it to the constructor of the ImportController class, like so:
(new ImportController(new Response, new ImportController))->updateOrCreateInventory($id);
I get an error that I am not passing dependencies to Response and ImportController. How can I make this work?
Have you tried to use app()->make()?
If not, try it:
if(!$inventory) {
$controller = app()->make(ImportController::class);
$controller->updateOrCreateInventory($id);
} else {
return '/' . $inventory->url;
}
Also, I don't think you are doing it in the right way. I think you should move the function updateOrCreateInventory to some service and in your trait create a instance of this service.
sorry for my english.
stack: Slim 3 framework + Eloquent ORM.
Eloquent works as expected with Slim.
I want to use sort of a MVC pattern where thin controllers and fat models(all db queries and other heavy logic).
All I found is how to use it from routes like this:
$app->get('/loans', function () use ($app) {
$data = DB::table('loan_instalment')->get(); // works
$data = $this->db->table('loan_instalment')->get(); // works
...
}
What I want is ability to call public methods from choosen model, something like this:
use \src\models\Instalment;
$app->get('/loans', function () use ($app) {
$data = $this->model('Instalment')->getSomething(12);
...
}
and Model class is:
namespace src\models;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Capsule\Manager as DB;
class Instalment extends Model
{
protected $table = 'loan_instalment';
public function getSomething($id)
{
return $this->table->find($id);
}
// bunch of other methods
}
My app looks like basic Slim skeleton, Eloquent settings:
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container['db'] = function ($container) use ($capsule){
return $capsule;
};
Is it possible ?
If you want to use MVC pattern, you need to make base controller.
<?php
namespace App\Controller;
use Slim\Container;
class BaseController
{
protected $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function getContainer()
{
return $this->container;
}
public function __get($name)
{
return $this->container->{$name};
}
public function __set($name, $value)
{
$this->container->{$name} = $value;
}
}
And the container:
// Base Controller
$container[App\Controller\BaseController::class] = function ($c) {
return new App\Controller\BaseController($c);
};
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container['db'] = function ($container) use ($capsule){
return $capsule;
};
Highly recommended to use static function on models
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model as Model;
use Illuminate\Database\Capsule\Manager as DB;
class Instalment extends Model
{
protected $table = 'loan_instalment';
public static function getSomething($id)
{
return Instalment::find($id);
}
}
And now you code become:
<?php
use App\models\Instalment;
$app->get('/loans', function ($request, $response, $args) {
$data = Instalment::getSomething(12);
...
}
The controller:
<?php
namespace App\Controller;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use App\models\Instalment;
class HomeController extends BaseController
{
public function __invoke(Request $request, Response $response, Array $args)
{
$data = Instalment::getSomething(12);
// load the template
return $response;
}
}
And the route for the controller
<?php
$app->get('/', App\Controller\HomeController::class);
It looks cleaner, isn't it?
More tutorial:
My Blog
Rob Allen's Blog
You could use the abbility of Slim to use controllers.
Make a basic controller:
// BasicController.php
<?php
namespace src\Controllers;
class BasicController
{
public function model(string $model)
{
return new $model();
}
}
and then in your controllers extend this class and add it to the slim container
//SomeController.php
<?php
namespace src\Controllers;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \src\models\Instalment as Instalment;
class SomeController extends BasicController
{
public function index(Request $request, Response $response, $args)
{
$this->model(Instalment::class)->getSomethingOutOfDB;
//do something else
}
}
...
//container.php
use \Slim\Container as Container;
$container[\src\Controllers\HomeController::class] = function(Container $container) {
return new \src\Controllers\Homecontroller();
}
...
...
//routes.php
$app->get('/someroute', \src\Controllers\HomeController::class . ':index');
...
Another possibility is to extend your \Slim\App by:
//newApp.php
namespace scr\App
class newApp extends \Slim\App
{
public function model(string $model)
{
return new $model();
}
}
I actually would advice against these both methods, and not load your models in this way, since this is considered bad practice.
It is better just to use:
//routes.php
...
use src\Models\Instalment;
...
...
$app->get('/someroute', function() {
$instalment = new Instalment();
// do something with it...
});
Hello guys I'm using laravel 5 polymorphic relation to save the data in the database but I'm facing some problem. When ever I try to save the data in the database it is throwing me this error
Call to a member function save() on null
I don't know why I'm facing this error. I'm following this tutorial fot the polymorphic relation Creating Polymorphic Relations in Laravel 5.
I 'm making a polymorphic relation like this. A post and comment can have many likes.
The like Request validates that if I'm sending a id then this request should be entertained otherwise not
Like Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\LikeRequest;
use App\Commands\LikeCommand;
// use App\Commands\ReadLikeCommand;
use App\Http\Controllers\Controller;
use Illuminate\Bus\Dispatcher;
// use App\Transformers\PostTransformer;
use Exception;
// use App\Events\TestEvent;
use App\Exceptions\Custom\NotPermissionException;
use App\Exceptions\Custom\NameNotFound;
class LikeController extends Controller
{
public function likeComment(LikeRequest $data){
try{
$render = $this->dispatch(new LikeCommand("comment" , $data));
}catch(Exception $e){
$e->getMessage();
}
}
public function likePost(LikeRequest $data){
error_log("1");
try{
$render = $this->dispatch(new LikeCommand("post" , $data));
}catch(Exception $e){
error_log("error : ".$e->getMessage());
}
}
}
Like Command
<?php
namespace App\Commands;
use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Repositories\LikeRepository;
use Exception;
use DB;
use App\LikeModel;
use Artisan;
use App\Repositories\PostRepository;
class LikeCommand extends Command implements SelfHandling
{
use DispatchesJobs;
private $postId;
private $action;
private $data;
/**
* Create a new command instance.
*
* #param $request
*
* #internal param $email
* #internal param $phone
* #internal param $comments
* #internal param $name
*/
public function __construct($action,$request)
{
$this->action = $action;
$this->postId = $request->id;
$this->data = $request;
error_log("Hello in the construct");
}
/**
* Execute the command.
*
* #param TestRepository $TestRepository
*/
public function handle(LikeRepository $LikeRepo, PostRepository $postRepo )
{
error_log("Hello");
error_log("A : ".$this->action );
error_log("ID : ".$this->postId);
if($this->action =="comment"){
error_log("in like comment");
return $LikeRepo->LikeComment( $this->postId);
}else if ($this->action == "post"){
error_log("2");
return $LikeRepo->LikePost( $this->postId, $postRepo , );
}
}
}
Like Repo
<?php
namespace App\Repositories;
use App\Repositories\CommentRepository;
use App\Repositories\PostRepository;
use App\CommentModel;
use App\LikeModel;
class LikeRepository
{
public function create($comment)
{
// error_log("Trying to save now. Let's see");
$Like = new LikeModel;
$Like->post_id = $comment;
// $Comment->post_id = $this->post_id;
$comment->save();
}
public function LikeComment($id) {
// return CommentModel::where('post_id' , $id)->get();
// return CommentModel::get();
}
public function LikePost($id, PostRepository $postRepo){
error_log("3");
$result = $postRepo->getById($id);
error_log("4");
// $Like = DB::transaction(function () use ($LikeRepository) {
$Like = new likeModel;
error_log("5");
$result->Like->save($like);
error_log("6");
$Like->status="success";
// });
return $Like;
}
}
Like Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LikeModel extends Model
{
public $table = "likes";
//
public function likeable()
{
return $this->morphTo();
}
}
Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PostModel extends Model
{
//
public $table = "posts";
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
}
Comment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CommentModel extends Model
{
//
public $table = "comments";
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
}
Update
I solved this problem by changing $result->Like->save($like); to this $result->likes->save($like); and int he PostModel I had to change App\Likes to App\LikeModel similarly in CommentModel but now it's throwing me this error error : Method save does not exist.
Your problem in updated version was getting collection of likes but not relation which you need to run $relation->save($like).
See updated code below:
public function LikePost($id, PostRepository $postRepo){
$result = $postRepo->getById($id);
$Like = new likeModel;
error_log("5");
$result->likes()->save($Like);
error_log("6");
$Like->status="success";
return $Like;
}
I am new to Laravel 5 and Pingpong-Modules https://github.com/pingpong-labs/modules
I want to Access from an outsite of the Modules-Directory to a Specific Module-Function.
My Actual Configuration is:
I want to access to the Method "test()" from the DashboardController - what is here the best practice?
Code of Controller 1:
<?php namespace App\Http\Controllers\Admin;
use App\Http\Controllers\AdminController;
use App\News;
use App\NewsCategory;
use App\User;
use App\Video;
use App\VideoAlbum;
use App\Photo;
use App\PhotoAlbum;
use \Pingpong\Modules\Facades\Module;
use App\Helpers\ModulesHelper;
class DashboardController extends AdminController {
public function __construct()
{
parent::__construct();
}
public function index()
{
$title = "Dashboard";
$news = News::count();
$newscategory = NewsCategory::count();
$users = User::count();
$photo = Photo::count();
$photoalbum = PhotoAlbum::count();
$video = Video::count();
$videoalbum = VideoAlbum::count();
return view('admin.dashboard.index', compact('title','news','newscategory','video','videoalbum','photo',
'photoalbum','users'));
}
Code of Controller 2:
<?php namespace Modules\Users\Http\Controllers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\View;
class UsersController extends Controller {
public function index()
{
return View::make('users::index');
}
public function test() {
return "TEST";
}
}
Put this block wherever you want in DashboardController:
$usersController = App::make('Modules\Users\Http\Controllers\UsersController');
$usersController->test();