Laravel get instance in a model - php

First please be gentle i am a beginner and im only coding for practise.
I try to pass an instance to the model but i always get this error
Argument 1 passed to Store::__construct() must be an instance of Illuminate\Filesystem\Filesystem, none given
my model
<?php
use Illuminate\Filesystem\Filesystem as File;
class Store extends Eloquent
{
public $timestamps = false;
public function __construct(File $file)
{
$this->file = $file;
}
}
Could please somebody tell me what i am doing wrong?
thank you
EDIT
I just used simply like this in my Controller
public function index()
{
$store = new Store;
return View::make('store', $store);
}

The File class is one of Laravels Facades, which means you do not need to pass it into your models construct.
You can access it from anywhere in Laravel using File::someMethod(). If you use namespaces then you have to access via the root namespace \File::someMethod().
Within your store view you can access the File facade directly with the aforementioned method.
Take a look at the documentation on the file system here http://laravel.com/api/class-Illuminate.Filesystem.Filesystem.html
So you can use File::copy() without having to instantiate a class as it is called from a static method.

Related

How does this Facade works

I'm working with Laravel 5.8 and it's an Online Store project written by other programmers.
Basically I have faced something weird that never seen before.
Let's say we have this at a Controller method:
$payment = CourseRegistrationFacade::insertCourseRegisterInformation($courseId,$date,$memberId,$userId);
And then we goto the CourseRegistrationFacade and it goes like this:
class CourseRegistrationFacade extends BaseFacade
{
}
So the whole class is empty but it extends another Facade which is BaseFacade and it goes like this:
class BaseFacade extends Facade
{
protected static function getFacadeAccessor()
{
return static::class;
}
protected static function shouldProxyTo($class)
{
app()->bind(self::getFacadeAccessor(), $class)
}
}
And that's it !
I don't really know where the heal is insertCourseRegisterInformation !!
So if you know how this Facade works, please let me know...
Here is the full code of BaseFacade.php:
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class BaseFacade extends Facade
{
protected static function getFacadeAccessor()
{
return static::class;
}
public static function shouldProxyTo($class)
{
app()->bind(self::getFacadeAccessor(), $class);
}
}
Search in the code for:
CourseRegistrationFacade::shouldProxyTo(
Most likely in the service provider that line is somewhere registering that facade to some concrete implementation of a class. Then check the contents of the class (the argument passed to shouldProxyTo).
Inside that class there should be a method called insertCourseRegisterInformation.
The way facades work is they resolve the class out of the container and then call the method you call statically.
So for example, let's say you have a UserService.php with a method register() and that class is mapped to a UserServiceFacade.php. When you do UserServiceFacade::register(), __callStatic will get the facade accessor (actual class) from the container, then call the register() method of that class.
You can understand better by inspecting __callStatic inside Facade.php.
Essentially UserServiceFacade::register() is the same as doing:
$userService = app()->make(UserService::class);
$userService->register()
By using the facade you can hide the concrete implementation and could possibly switch it to something else in the future by just changing it in a single place.
I think there must be a Provider exists for that Facade which is initializing its associated class and insertCourseRegisterInformation method definition must be declared in it. Please find that provider and then you'll find its associated class from that Provider code. I think you can find all registered providers from config/app.php
These reference articles might help you.
Reference 1:
https://grafxflow.co.uk/blog/mvc/adding-global-custom-class-facades-laravel-5
Reference 2: http://www.expertphp.in/article/how-to-create-custom-facade-in-laravel-52

Laravel 5.8 newing up eloquent model and calling accessor in one line?

I have a contact_info_scopes table and one of the scopes is 'Default', which is likely to be the most common scope called, so I'm creating an accessor
public function getDefaultScopeIdAttribute()
{
return $this::where('contact_info_scope', 'Default')
->first()
->contact_info_scope_uuid;
}
to get the defaultScopeId and wondering how I can new up the ContactInfoScope model and access that in one line. I know I can new it up:
$contactInfoScope = new ContactInfoScope();
and then access it:
$contactInfoScope->defaultScopeId;
but I would like to do this in one line without having to store the class in a variable. Open to any other creative ways of tackling this as well since an accessor may not really be ideal here! I'd be fine with just creating a public function (not as an accessor), but would have the same issue of calling that in one line. Thanks :)
You should be able to call the model and chain the value if you return the instance in its constructor method
(new ContactInfoScope)->defaultScopeID
Not tried it in Laravel but works in plain ol PHP
//LARAVEL
//write on model ----------------------------------
protected $appends = ['image'];
public function getImageAttribute()
{
$this->school_iMage = \DB::table('school_profiles')->where('user_id',$this->id)->first();
$this->studend_iMage = \DB::table('student_admissions')->where('user_id',$this->id)->first();
return $this;
}
//call form anywhere blade and controller just like---------------------------
auth()->user()->image->school_iMage->cover_image;
or
User::find(1)->image->school_iMage->cover_image;
or
Auth::user()->image->school_iMage->cover_image;
// you can test
dd( User::find(1)->image);

Load and use Codeigniter model in non Codeigniter class

I was just wondering if there is a way to use codeigniter model in other non Codeigniter classes... Let me give you an example.
I have this MyTestClassTests class which extends PHPUNIT_Framework_testCase
<?php
require_once '../../vendor/autoload.php';
use Facebook\WebDriver\Remote\WebDriverCapabilityType;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\Interactions\WebDriverActions;
use Sunra\PhpSimple\HtmlDomParser;
class MyTestClassTests extends PHPUnit_Framework_TestCase
{
public function testDoSomething()
{
// Do some test
// get results
// Store results via Codeigniter Model, if possible?
$results = 'some results';
$this->load->model('results');
$this->results->import($results);
}
}
Now once test is finished i would like to store test results in to the database. Is there a way to call/initialize CodeIgniter model in current class to use it and store data? This file is located in the Codeigniters controllers folder.
If you need any additional information's please let me know and i will provide. Thank you!
Since you appear to be unit testing you should consider using ci_phpunit-test which makes it much easier to use PHPUnit with CodeIgniter 3.x.
Because you're unit testing the following may not apply. These examples only work within an fully instantiated CI framework. Within that context there are a couple ways to give a stand-alone class access to the CI object.
One approach is to capture the CI instance in a class property.
class MyTestClassTests extends PHPUnit_Framework_TestCase
{
protected $CI;
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI = & get_instance();
}
public function testDoSomething()
{
// Do some test
// get results
// Store results via Codeigniter Model, if possible?
$results = 'some results';
//use the class property to access CI classes and methods
$this->CI->load->model('results');
$this->CI->results->import($results);
}
}
A second approach uses the PHP magic method __get. The advantage is it's much easier to write the code. The disadvantage is it's a tiny bit less efficient because extra code is executed each time you access the CI instance.
class MyTestClassTests extends PHPUnit_Framework_TestCase
{
/**
* Enables the use of CI super-global without having to define an extra variable.
*
* #param $var The CI property or method to access
* #return mixed
*/
public function __get($var)
{
return get_instance()->$var;
}
public function testDoSomething()
{
// Do some test
// get results
// Store results via Codeigniter Model, if possible?
$results = 'some results';
//you get to write code as if you were part of the CI object.
//IOW, you write code normally
$this->load->model('results');
$this->results->import($results);
}
}
In order to use codeigniter model in your non codeigniter class you have to instantiate CI first.
In your case below code will work.
$CI = & get_instance()
$CI->load->model('results');
$CI->results->your_function();

Call to undefined method after creating new model (Laravel 4.2)

I just set up a new model and I am trying to call a custom written static method that I've written from inside a new controller to match the model:
<?php
class NewModelWebController extends AjaxController {
public function newModelView() {
$loggedUser = Auth::user();
$data['user'] = $loggedUser;
$data['allDetails'] = NewModel::getFullWithDetails($loggedUser->user_id);
return View::make('webApp::new-model.view', $data);
}
}
Here is the method definition inside the model class (there are no spaces before the php declaration):
<?php
class NewModel extends Eloquent {
protected $table = 'new_models';
protected $primaryKey = 'new_model_id';
public static function getFullWithDetails($userId) {
return 1; // doesn't matter what I return -- the problem still happens
}
}
The error that is returned is the following:
Call to undefined method Illuminate\Database\Query\Builder::getFullWithDetails()
When I make calls such as NewModel::find(1); it works with no issues, but once I try to make calls on the method I wrote, it does not work.
I tried all of the following commands with no success:
composer update
composer dump-autoload
composer clear-cache
chown -R www-data:www-data ./theProjectFile
Thoughts are appreciated.
Try using scopes instead of actual static methods.
class NewModel extends Eloquent {
public function scopeGetFullWithDetails($userId)
{
//
}
}
Calling is the same. NewModel::getFullWithDetails(1);
I ended up having to recreate the model from scratch. There must have been a problem with file encoding or filetype when I initially created it because originally I just duplicated another model class and then changed the values inside. Creating a brand new file and then pasting the PHP content back in fixed the issue! Thanks for the help!

How to load models in Laravel?

I started studying Laravel and ran into a problem using models. How to load them? For example in CodeIgniter i used it like $model = $this->load->model('some_model'). In Laravel when i call it from controller like Sites::OfUser() it work fine, but when i call Sites::getId() it says that method should be static...
Is it possible to call method without static or i need to create facades for each model?
My model looks like this:
namespace Models;
use Eloquent;
class Sites extends Eloquent {
public function scopeOfUser($query)
{}
public function getId($name)
{}
}
For static method--
$type = Sites ::scopeOfUser($query);
and if you want normal like codeingiter then use--
$model = new Sites ();
$type = $model->scopeOfUser($query);
You can of course make a static method in the model, and do some static work in it (get ID for name or whatever).
That's no problem.
However, you must declare it static if you want to use the ::, which you are doing not.
public static /* <-- this */ function getId($name)
{
// Do work
// return $result;
}
If you want to access a method with ::, you will need to make it a static method or create a Facade.
The reason why Sites::OfUser() is "working" is because you have prefixed that method with scope.
Scopes allow you to easily re-use query logic in your models. To
define a scope, simply prefix a model method with scope.
If you want to use Facades you can follow my answer here on how to create a Facade.

Categories