I am creating my model object using new keyword. But each time the two objects created. My code is
class DashBoardController extends Controller
{
public static $count=0;
public function __construct()
{
DashBoardController::$count++;
}
public function dashboard(Request $request)
{
$obj = new DashBoardController();
echo DashBoardController::$count;
}
}
It gives me output as
O/P: 2
The result is right, there are two instances of DashboardController: The one created by the routing and then the one created by the dashboard method.
It seems that it's better yo use $this instead of creating a new instance of a controller.
Inside the dashboard method you are inside an already existing controller!
Related
I want to create a global array inside a controller class in laravel. I searched and explored many resources but couldn't find a proper answer. I want that array to be accessible by all the methods in that controller. Currently I have tried this :
public $members=array(1,2); Global variable
`global $members;` //Inside function
echo $members[0]; //Inside function
I tried to access the data in the array in the function but got a null exception.Please help me out.
You should use the $this keyword.
class x extends Controller {
public $members = array(1,2);
public function myAction(){
echo $this->members[0];
}
}
I have a model in laravel and I want to do something after the first time which an object of my model is created. the simplest way is to add a static boot method inside my model's class like the code below:
class modelName extends Model
{
public static function boot()
{
parent::boot();
self::created(function ($model) {
//the model created for the first time and saved
//do something
//code here
});
}
}
so far so good! the problem is: the ONLY parameter that created method accepts is the model object itself(according to the documentation) :
Each of these methods receives the model as their only argument.
https://laravel.com/docs/5.5/eloquent#events
I need more arguments to work with after model creation. how can I do that?
Or is there any other way to do something while it's guaranteed that the model has been created?
laravel version is 5.5.
You're close. What I would probably do would be to dispatch an event right after you actually create the model in your controller. Something like this.
class WhateverController
{
public function create()
{
$model = Whatever::create($request->all());
$anotherModel = Another::findOrFail($request->another_id);
if (!$model) {
// The model was not created.
return response()->json(null, 500);
}
event(new WhateverEvent($model, $anotherModel));
}
}
I solved the issue using static property in eloquent model class:
class modelName extends Model
{
public static $extraArguments;
public function __construct(array $attributes = [],$data = [])
{
parent::__construct($attributes);
self::$extraArguments = $data ;
public static function boot()
{
parent::boot();
self::created(function ($model) {
//the model created for the first time and saved
//do something
//code here
self::$extraArguments; // is available in here
});
}
}
It works! but I don't know if it may cause any other misbehavior in the application.
Using laravel events is also a better and cleaner way to do that in SOME cases.but the problem with event solution is you can't know if the model has been created for sure and it's time to call the event or it's still in creating status ( and not created status).
So here's the code
use App\Video;
class HomeController extends Controller
{
protected $video;
public function index()
{
// $video_to_watch is fetched from db and I want to save it and use it in
// another function in this controller
$this -> video = $video_to_watch;
return view('home', compact('video_to_watch'));
}
public function feedback(Request $request)
{
dd($this -> video);
}
}
feedback returns null for some reason.
when I put the
dd($this -> video);
in index() it works fine, not null.
I have tried what's suggested here: Laravel doesn't remember class variables
but it didn't help.
I'm sure it's something stupid I'm overlooking. But can't seem to figure out what, any help much appreciated.
You can't keep your $video value between 2 different requests. You have to fetch your video data in each request.
use App\Video;
class HomeController extends Controller
{
public function index() {
$myVideo = $this->getMyVideo();
return view('home', $myVideo);
}
public function feedback(Request $request) {
dd($this->getMyVideo);
}
private function getMyVideo() {
// fetch $video_to_watch from db
return $video_to_watch ;
}
}
First of all don't fetch data inside a Controller. It's only 'a glue' between model and view. Repeat. No fetching inside a controller.
Use domain services and dependency injection to get business data and if you want to share this data create shared service (single instance).
-
Putting a data object into a controller property class makes a temporary dependency between method calls. Avoid it. Use services instead.
I look at many search results with this trouble but i can`t get it to work.
The User Model:
<?php namespace Module\Core\Models;
class User extends Model {
(...)
protected function Person() {
return $this->belongsTo( 'Module\Core\Models\Person', 'person_id' );
}
(...)
And the Person Model:
<?php namespace Module\Core\Models;
class Person extends Model {
(...)
protected function User(){
return $this->hasOne('Module\Core\Models\User', 'person_id');
}
(...)
Now, if i use User::find(1)->Person->first_name its work. I can get the Persons relations from the User Model.
But.. User::with('Person')->get() fails with a Call to undefined method Illuminate\Database\Query\Builder::Person()
What im doing wrong? i need a collection of all the users with their Person information.
You have to declare the relationship methods as public.
Why is that? Let's take a look at the with() method:
public static function with($relations)
{
if (is_string($relations)) $relations = func_get_args();
$instance = new static;
return $instance->newQuery()->with($relations);
}
Since the method is called from a static context it can't just call $this->Person(). Instead it creates a new instance of the model and creates a query builder instance and calls with on that and so on. In the end the relationship method has to be accessible from outside the model. That's why the visibility needs to be public.
this supposed to be an MVC framework
(i am learning by doing)
class load{
public function model(){
// some code...
[...] = model[$modelName] = new $modelName();
}
}
this class handles all load option in to the controller..
class _framework{
public $load; // object
public $model; // array
function __construct(){
//some code...
$this->load = new load();
}
}
this is the framework of the controllers
the controller extends this class.
edit:
it should use like this:
class newController extends _framework{
public function index(){
$this->load->model('modelName'); // for loading the model.
$this->model['modelName']->modelMethod(); // for use the model method.
}
}
my problem is where the [...].
how can I get the new model to the array in the framework class??
If you want to get an array out of your model object,
you can define its public method toArray:
class modelName {
public function toArray () {
$array = ...; // get your array here
return $array;
}
}
Then you can call it from outside and get your array:
$myArray = $myModel->toArray();
Your model should encapsulate its data and make them accessible via API like that.
I would not call an array a model though. A model is a layer with many classes serving the purpose of the model - storing your data, peforming their validation, whatever other data-related business logic and providing API to access the data.
Also it is common to capitalize your classes.