I am trying to understand the usage and difference of boot and booted.
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected static function boot() {
parent::boot();
static::creating(function ($user) {
});
}
protected static function booted() {
parent::booted();
static::creating(function ($user) {
});
}
}
When and where should be this two function called?
Actually answer is in the Eloquent model itself:
protected function bootIfNotBooted()
{
if (! isset(static::$booted[static::class])) {
static::$booted[static::class] = true;
$this->fireModelEvent('booting', false);
static::booting();
static::boot();
static::booted();
$this->fireModelEvent('booted', false);
}
}
/**
* Perform any actions required before the model boots.
*
* #return void
*/
protected static function booting()
{
//
}
/**
* Bootstrap the model and its traits.
*
* #return void
*/
protected static function boot()
{
static::bootTraits();
}
/**
* Perform any actions required after the model boots.
*
* #return void
*/
protected static function booted()
{
//
}
I tried both, I think there are just the same; just that boot will run first and it requires to call extra parent::boot()
protected static function boot()
{
parent::boot();
self::creating(function (Outlet $outlet): void {
Log::debug("#boot");
$outlet->name = "boot";
});
}
protected static function booted()
{
self::creating(function (Outlet $outlet): void {
Log::debug("#booted");
$outlet->name = "booted";
});
}
Related
I'm mocking a Repository inside the controller, but when I call CompanyController#index (which in turn calls CompanyRepository#all), tests returns this error:
Test\Unit\Shared\Repositories\CompanyRepositoryTest::test_all
Mockery\Exception\InvalidCountException: Method all() from Mockery_0__App_Shared_Repostiries_CompanyRepository should be called
exactly 1 time but called 0 times.
<?php
namespace Test\Unit\Shared\Repositories;
use Mockery;
use Tests\TestCase;
class CompanyRepositoryTest extends TestCase
{
protected $companyRepo;
protected $company;
public function setUp(): void
{
parent::setUp();
}
public function tearDown(): void
{
parent::tearDown();
}
/**
* #group mockingrepo3
*/
public function test_all()
{
$this->companyRepo = Mockery::mock('\App\Shared\Repositories\CompanyRepository');
$this->companyRepo->shouldReceive('all')
->andReturn(new \Illuminate\Support\Collection)
->once();
$this->company = \App\Models\Company::find(3);
$this->be($this->company);
$this->app->instance('\App\Shared\Repositories\CompanyRepository', $this->companyRepo);
$response = $this->call('GET', route('app.admin.company.index'));
// $this->assertEquals(new \Illuminate\Support\Collection, $companies);
}
}
CompanyController
<?php
class CompanyController extends Controller
{
private $companyRepo;
public function __construct(CompanyRepository $companyRepo)
{
$this->companyRepo = $companyRepo;
}
public function index(Request $request)
{
$companies = $this->companyRepo->all();
return view("admin.company.index")->with(['companies' => $companies]);
}
}
i have setup a Laravel project with two guards wach with Hi own users table. Now i want to save the sessions into the database instead in a file. The Problem is that I cant save the session in a single table, because the user ID is not unique.
How can I solve this problem? Thanks.
I tried this. This working, but it exists a default session driver, so a user has a session in the default table and in the admin_sessions table.
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Administrator::class => UserPolicy::class,
];
public function boot()
{
$this->registerPolicies();
Auth::extend('admin_session', function ($app, $name, array $config) {
$provider = Auth::createUserProvider($config['provider']);
$guard = new SessionGuard($name, $provider, $app->session->driver('admin_database'));
if (method_exists($guard, 'setCookieJar')) {
$guard->setCookieJar($this->app['cookie']);
}
if (method_exists($guard, 'setDispatcher')) {
$guard->setDispatcher($this->app['events']);
}
if (method_exists($guard, 'setRequest')) {
$guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
}
return $guard;
}
}
class SessionServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
}
/**
* Perform post-registration booting of services.
*
* #return void
*/
public function boot()
{
$this->app->session->extend('admin_database', function ($app) {
$table = 'administrator_sessions';
// This is not workin, because I don't have the user her.
/*if (auth()->user() instanceof Customer) {
$table = 'customer_sessions';
}
else if (auth()->user() instanceof Administrator){
$table = 'administrator_sessions';
}*/
$lifetime = $app['config']['session.lifetime'];
$connection = $app['db']->connection($app['config']['session.connection']);
return new DatabaseSessionHandler($connection, $table, $lifetime, $app);
});
}
}
This is how I create helper (App\Helpers\Settings.php)
namespace App\Helpers;
use Illuminate\Database\Eloquent\Model;
class Settings {
protected $settings = [];
public function __construct() {
$this->settings['AppName'] = 'Test';
}
/**
* Fetch all values
*
* #return mixed
*/
public function getAll () {
return $this->settings;
}
}
Creating facade (App\Helpers\Facades\SettingsFacade.php)
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Settings extends Facade {
protected static function getFacadeAccessor() {
return 'Settings';
}
}
Creating Service Provider (App\Providers\SettingsServiceProvider.php)
namespace App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
class SettingsServiceProvider extends ServiceProvider {
/**
* Bootstrap the application events.
*
* #return void
*/
public function boot() {
}
/**
* Register the service provider.
*
* #return void
*/
public function register() {
App::bind( 'Settings', function () {
return new \App\Helpers\Settings;
});
} */
}
Registering provider (App\Providers\SettingsServiceProvider::class)
Creating alias: 'Settings' => App\Facades\Settings::class
Running composer dump-autoload
Trying to use facade Settings::getAll();
Getting error Class 'App\Http\Controllers\Settings' not found
Can’t figure out why I cannot create facade and getting that error
try this one.
App\Helpers\Settings.php
namespace App\Helpers;
use Illuminate\Database\Eloquent\Model;
class Settings {
protected $settings = [];
public function __construct() {
$this->settings['AppName'] = 'Test';
}
/**
* Fetch all values
*
* #return mixed
*/
public function getAll () {
return $this->settings;
}
}
App/Http/Controllers/XyzController.php
use Facades\App\Settings;
class XyzController extends Controller
{
public function showView()
{
return Settings::getAll();
}
}
web.php
Route::get('/','XyzController#showView');
use Facades\App\Helpers\Settings;
Route::get('/direct',function() {
return Settings::getAll();
});
use laravel Real time facades
am trying to call functions inside my model in my controller but i get this error.
(1/1) ErrorException Non-static method App\User::getallreferrals() should not be called statically. in HomeController.php (line 37)
this is my model.
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Auth;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','last_name','other_name','user_name','number2','email', 'password', 'number','bank_name','acct_number','acct_name', 'next_kin', 'next_kin_no', 'transaction_details', 'entry_matrix','referral_id', 'referred_by','first_downline_id', 'second_downline_id'
];
/**
* The attributes that should be hidden for arrays. `1
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function scopeGetallreferrals($query)
{
return $query->where('referred_by', Auth::user()->referral_id)->pluck('referral_id');
}
public function scopeGetallreferralsobject($query)
{
return $query->where('referred_by', Auth::user()->referral_id)->get();
}
public function scopeGetallreferrals2genobject($query)
{
$referrals = $this->getallreferrals();
return $query->where('referred_by', $referrals)->get();
}
public function scopeGetallreferrals2gen($query)
{
$referrals = $this->getallreferrals();
return $query->where('referred_by', $referrals)->pluck('referral_id');
}
public function scopeGetallreferrals3gen($query){
$referrals2gen = $this->getallreferrals3gen();
return $query->where('referred_by', $referrals2gen)->pluck('referral_id');
}
public function scopeGetcaptain($query)
{
return $query->where('referral_id', Auth::user()->referred_by)->pluck('referred_by');
}
public function scopeGetallcaptain2gen($query)
{
$captain = $this->getcaptain();
return $query->where('referral_id', $captain)->pluck('referral_id');
}
public function scopeGetallcaptain3gen($query){
$captain2gen = $this->getcaptain2gen();
return $query->where('referred_by', $captain2gen)->pluck('referral_id');
}
public function scopeGetallreferralsbyID($query, $id){
return $this->getallreferrals()->where('id', $id);
}
public function scopeGetallreferrals2genbyID($query, $id){
return $this->getallreferrals2gen()->where('id', $id);
}
public function scopeGetallreferrals3genbyID($query, $id){
return $this->getallreferrals3gen()->where('id', $id);
}
}
then my controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\DateTime;
use App\User;
use Auth;
use Session;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$captain = User::getcaptain();
$referrals = User::getallreferrals();
return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}
Please what am i not doing right? I have been on this project for a while now.
my migrations
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('other_name');
$table->string('user_name');
$table->string('number');
$table->string('number2');
$table->string('bank_name');
$table->string('acct_number');
$table->string('acct_name');
$table->string('email')->unique();
$table->string('password');
$table->string('next_kin');
$table->string('next_kin_no');
$table->string('entry_matrix');
$table->string('transaction_details')->nullable();
$table->integer('isconfirmed')->default(0);
$table->string('total_earned')->nullable();
$table->string('total_paid')->nullable();
$table->string('type_account')->nullable();
$table->integer('stage')->default(0);
$table->string('referral_id')->unique();
$table->string('referred_by')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
As it is saying the getallreferrals method is not static, but you are trying to call it with :, which means static.
It should be something like
use a Scope for this in User model
public function scopeGetallreferrals($query, $user)
{
return $query->where('referred_by', $user->referral_id);
}
and in controller
public function __construct(User $user)
{
$this->middleware('auth');
$this->user = Auth:user();
}
public function index()
{
$captain = $this->user->getcaptain();
$referrals = $this->user->getallreferrals($this->user)->pluck('referral_id');
return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}
I have a service-providers here as well as http://dfg.gd/blog/decoupling-your-code-in-laravel-using-repositiories-and-services
My ServiceProvider:
class UsersRepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('App\Repositories\Users\UsersInterface', function($app)
{
return new UsersRepository(new User);
});
}
And i get error: Call to a member function find() on a non-object
My Repository:
use \Illuminate\Database\Eloquent\Model;
//..
protected $usersModel;
public function __consturct(Model $users)
{
$this->usersModel = $users;
}
/**
* Get user by id
*
* #param mixed $userId
* #return Model
*/
public function getUserById($userId)
{
return $this->convertFormat($this->usersModel->find($userId));
}
__consturct is misspelled.
correct is __construct