If I want to set a variable that my whole controller can access, how do I do it?
Right now, in every function I am setting
$id = $this->session->userdata('id');
I'd like to be able to access $id from any function w/o defining it for each controller. :)
If there's a better way, I'm all ears! I'm a noob!
To elaborate on Koo5's response, you'll want to do something like this:
class yourController extends Controller {
// this is a property, accessible from any function in this class
public $id = null;
// this is the constructor (mentioned by Koo5)
function __construct() {
// this is how you reference $id within the class
$this->id = $this->session->userdata('id');
}
function getID() {
// returning the $id property
return $this->id;
}
}
See the manual for more information on PHP properties and constructors. Hope that helps!
If with global you mean the scope of a single controller, the above answers are correct. If you want to access variables from multiple controllers, I recommend defining a BaseController class and then extending your normal controllers to inherit from that BaseController:
class yourController extends BaseController {}
I use this all the time for both global variables and methods.
Define that very line in a constructor only
You can use this method too inside your controller
function __construct() {
// this is how you reference $id within the class
DEFINE("userId",$this->session->userdata('id'));
}
And Call It As :
function getID() {
// returning the $id property
return userId;
}
Related
When a request comes to Laravel controller through application router, how can we determine which method is called inside that controller? I mean inside constructor or magic methods of the controller. Is it possible to know?
Consider the method that is called exists. So __call would not be the solution.
I have this Route:
Route::get('exam', [ExamController::class,'index']);
And I want to get index inside ExamController class. maybe in side __construct or ...
public function __construct()
{
// here I want to access the name of called method
}
__call magic method just give the method name if the method is'nt exist:
public function __call($method, $parameters)
{
// I have access to $method name here (index)
}
You can use the __FUNCTION__ or __METHOD__ PHP constants to obtain information about the function or class and function:
class SomeClass
{
public function aFunction()
{
echo __FUNCTION__;
}
public function anotherFunction()
{
echo __METHOD__;
}
}
$obj = new SomeClass();
$obj->aFunction(); // aFunction
$obj->anotherFunction(); // SomeClass::anotherFunction
Update
Let's assume whilst you might not have a function defined for a specific route, you know the name of a route you want to apply a specific middleware to. You can apply middelware to specific functions from the controller constructor:
public function __construct()
{
$this->middleware('auth', ['only' => ['index', 'create']]);
}
Alternatively just specify the middleware required for the route on the route definition.
How to use __construct on laravel eloquent and get attributes. I tired:
public function __construct() {
parent::__construct();
dd($this->attributes);
}
My code return null. But on abstract class Model filled all attributes:
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->initializeTraits();
$this->syncOriginal();
$this->fill($attributes);
}
It's possible get access to model attributes in the constructor method?
Try with accessors.
https://laravel.com/docs/5.8/eloquent-mutators#accessors-and-mutators
Define it like:
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
And use $this->first_namesomething like this.
I tested this locally by updating the constructor like this:
public function __construct(array $attributes = []) {
parent::__construct($attributes);
dd($this->getAttributes());
}
However, I've discovered that when fetching the object from the database, its attributes are not filled in the constructor, and therefore it's not possible to access them there.
What you can do is access the attributes after the object has been initialized:
$post = Post::find(1);
dump($post->getAttributes());
Not sure if that helps, but it is what it is.
Maybe Events or Observers can help you with what you need:
https://laravel.com/docs/5.8/eloquent#events
https://laravel.com/docs/5.8/eloquent#observers
It's impossible in constructor, because attributes list is empty.
But you can use Events and boot() method of model to achieve desired result:
class MyModel extends Model{
public static function boot(){
parent::boot();
self::retrieved(function ($model) {# Called after data loaded from db
dd($this->attributes); # now attributes was filled
});
}
}
Read more about another events here:
https://www.itsolutionstuff.com/post/laravel-model-events-tutorialexample.html
I need to pass select option value from store method to show
i need to pass the $typeg value to show method
public function store(Request $request ) {
$typeg = $request->input('type');
}
public function show($id) {
dd($this->store($typeg));
}
i get
Undefined variable:
or
Too few arguments to function app\Http\Controllers\appController::show(), 1 passed and exactly 2 expected
Try this
on the first function you have some variable witch you want to pass it to another function\method
Than you need to use $this and the name of the other method you'd like to pass the var too something like this.
public function oneFunction(){
$variable = "this is pretty basic stuff in any language";
$this->anotherFunction($variable)
}
public function anotherFunction($variable){
dd($variable);
}
Store your data on session (or somewhere else like cookie, cache, database). So you can reach the data later.
class SomeController extends Controller {
public function store(Request $request ) {
session(["typeg"=>$request->input('type')])
}
public function show($id) {
dd(session("typeg"));
}
Is it possible to call a method from one controller inside another controller in Laravel 5 (regardless the http method used to access each method)?
This is how I have done it. Use the use keyword to make the OtherController available. Then you can call a method from that class on instantiation.
<?php namespace App\Http\Controllers;
use App\Http\Controllers\OtherController;
class MyController extends Controller {
public function __construct()
{
//Calling a method that is from the OtherController
$result = (new OtherController)->method();
}
}
Also check out the concept of a Command in Laravel. It might give you more flexibility than the method above.
use App\Http\Controllers\TargetsController;
// this controller contains a function to call
class OrganizationController extends Controller {
public function createHolidays() {
// first create the reference of this controller
$b = new TargetsController();
$mob = 9898989898;
$msg = "i am ready to send a msg";
// parameter will be same
$result = $b->mytesting($msg, $mob);
log::info('my testing function call with return value' . $result);
}
}
// this controller calls it
class TargetsController extends Controller {
public function mytesting($msg, $mob) {
log::info('my testing function call');
log::info('my mob:-' . $mob . 'my msg:-' . $msg);
$a = 10;
return $a;
}
}
I have a controller in Laravel 4, with a custom variable declared within it.
class SampleController extends BaseController{
public $customVariable;
}
Two questions: Is there any way I can call within a route filter:
The controller object where the filter is running at.
The custom variable from that specific controller ($customVariable).
Thanks in advance!
as per this post:
http://forums.laravel.io/viewtopic.php?pid=47380#p47380
You can only pass parameters to filters as strings.
//routes.php
Route::get('/', ['before' => 'auth.level:1', function()
{
return View::make('hello');
}]);
and
//filters.php
Route::filter('auth.level', function($level)
{
//$level is 1
});
In controllers, it would look more like this
public function __construct(){
$this->filter('before', 'someFilter:param1,param2');
}
EDIT:
Should this not suffice to your needs, you can allways define the filter inside the controller's constructor. If you need access to the current controller ($this) and it's custom fields and you have many different classes you want to have that in, you can put the filter in BaseController's constructor and extend it in all classes you need.
class SomeFancyController extends BaseController {
protected $customVariable
/**
* Instantiate a new SomeFancyController instance.
*/
public function __construct()
{
$ctrl = $this;
$this->beforeFilter(function() use ($ctrl)
{
//
// do something with $ctrl
// do something with $ctrl->customVariable;
});
}
}
EDIT 2 :
As per your new question I realised the above example had a small error - as I forgot the closure has local scope. So it's correct now I guess.
If you declare it as static in your controller, you can call it statically from outside the controller
Controller:
class SampleController extends BaseController
{
public static $customVariable = 'test';
}
Outside your controller
echo SampleController::$customVariable
use:
public function __construct()
{
$this->beforeFilter('auth', ['controller' => $this]);
}