Class 'App\Scope\__name_Scope' not found in lumen (Laravel micro-framework) - laravel

I want to add a global scope to my project. and use it in some models.
so I create this code: (in app/scopes folder)
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class GameStoreScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* #param Builder $builder
* #param Model $model
* #return void
*/
public function apply(Builder $builder, Model $model)
{
//$storeId = \request()->header('Store');
//dd("asdad");
$builder->where('game_store_id', '=', 1);
}
}
And use it to my model like this:
<?php
namespace App;
use App\Scopes\GameStoreScope;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
protected $guarded = [];
protected static function boot()
{
parent::boot();
static::addGlobalScope(new GameStoreScope);
}
but after run my project. always get this FatalError : Class 'App\Scopes\GameStoreScope' not found

Fix namespace ref link https://laravel.com/docs/8.x/eloquent#query-scopes
namespace App\Scopes;
use App\Scopes\GameStoreScope;
use Illuminate\Database\Eloquent\Model;
then run composer dump-autoload

Related

Trying to define a many-to-many relation with a pivot model in Laravel 8

Trying this for hours now and I don't see the error. I have a model 'User' and a model 'Round'. I want to define a n:m-relation with a model 'Flight' as pivot model.
User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
class User extends Authenticatable implements MustVerifyEmail, HasMedia
{
use Notifiable;
use InteractsWithMedia;
/*
.....
*/
public function rounds() {
return $this->belongsToMany(Round::class)->using(Flight::class);
}
}
Round.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Round extends Model
{
/*
.....
*/
public function users() {
return $this->belongsToMany(User::class)->using(Flight::class);
}
}
Flight.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Flight extends Pivot
{
public $incrementing = true;
/*
.....
*/
}
I made several migrations and seeder.
RelationSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Round;
class RelationSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$round = Round::find(1);
$round->users()->sync([1]);
}
}
When running artisan migrate:refresh --seed all tables are created as expected, but the following error occurs on seeding
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tour.round_user' doesn't exist (SQL: select * from round_user where round_id = 1)
Obviously Laravel is looking for a standard named pivot-table and not for the desired flights-table.
I am using Laravel 8 in a Docker-Container with Sail.
Where is my mistake?
I found my mistake. With using the pivot model, the name conventions for the intermediate table stay valid. It works with
public function rounds() {
return $this->belongsToMany(Round::class, 'flights')->using(Flight::class);
}
and same thing in the inverse definition
public function users() {
return $this->belongsToMany(User::class, 'flights')->using(Flight::class);
}
Thank you everybody who is helping here - I solved 1000s of problems reading your posts!

How to call Facades method from boot method?

In laravel 6 app I created facade app/Facades/MyFuncsClass.php :
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class MyFuncsClass extends Facade{
protected static function getFacadeAccessor() { return 'MyFuncsClass'; }
}
But I got error :
"message": "Non-static method App\\Helpers\\MyFuncsClass::debToFile() should not be called
statically",
calling it from boot method:
protected static function boot() {
parent::boot();
static::deleting(function($task) {
$hostel_image_image_path= Task::getTaskImagePath($task->id, $task->image);
MyFuncsClass::debToFile(print_r($hostel_image_image_path, true), '-9 $hostel_image_image_path::');
...
Is there is a way to escape this error and run MyFuncsClass::debToFile in boot method ?
MODIFIED :
Sure I registered my facade in config/app.php, 'providers' block :
...
App\Providers\MyFuncsClassProvider::class,
file app/Http/Helpers/MyFuncsClass.php has a lot of public methods, with heading:
<?php
namespace App\Helpers;
use Illuminate\Http\Request;
use Barryvdh\Debugbar\Facade as Debugbar;
use Carbon\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class MyFuncsClass {
public $concat_str_max_length = 50;
public $m_concat_str_add_chars = '...';
public function debToFile($contents, string $descr_text = '', bool $is_sql = false, string $file_name = '')
{
try {
...
and in app/Providers/MyFuncsClassProvider.php :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
class MyFuncsClassProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
App::bind('MyFuncsClass', function()
{
return new \App\Helpers\MyFuncsClass;
});
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
Actually I can call \MyFuncsClass::debToFile( ok from not static methods, like control actions, but I have the error
calling from static boot method...
MODIFIED # 2 :
With real time facades https://laravel.com/docs/5.7/facades#real-time-facades defintions
I tried
<?php
namespace App;
use DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Facades\MyFuncsClass;
use App\Http\Helpers\MyFuncsClassContainer; // Alias for my helper class
use Illuminate\Database\Eloquent\Model;
use Barryvdh\Debugbar\Facade as Debugbar;
class Task extends Model
{
use Sluggable;
protected $table = 'tasks';
protected $primaryKey = 'id';
}
protected static function boot() {
parent::boot();
static::deleting(function($task) {
$hostel_image_image_path= Task::getTaskImagePath($task->id, $task->image);
\Log::info( '-9 $hostel_image_image_path::' );
\Log::info( print_r($hostel_image_image_path, true) );
$myFuncsClassCore = factory(MyFuncsClassContainer::class)->create();
$myFuncsClassCore->debToFile(' debToFile string REDSA');
Bur anywat I got error :
Cannot declare class App\Helpers\MyFuncsClassContainer, because the name is already in use {"userId":1,"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalErrorException
I tried a way to rename my helper class to “MyFuncsClassContainer”, supposing
having the same name for helper and facade could raise error, but failed
If there is a way to fix this error ?
Thanks!

Enforce Global Scope Across all models

we are developing an application based on Laravel Spark. as part of this we want to tie resources to a specfic team.
I know that we can add a global scope such as:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class TeamScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #param \Illuminate\Database\Eloquent\Model $model
* #return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('team_id', '=',Auth()->user()->currentTeam->id );
}
}
but according to the docs we have to add that to each model that we want to restrict like so:
protected static function boot()
{
parent::boot();
static::addGlobalScope(new TeamScope);
}
my issue with this is that it will be possible to create future models and forget to apply this code. Which could give us a security hole?
is there any way to enforce the scope across the board?
I am not sure if there's a way to globally add the Scope.
In my particular application, we have had to add more responsiblities to our Models. So we created a BaseModel class that extends Laravel's Illuminate\Database\Eloquent\Model.
All new Models then extends the BaseModel instead of Laravel's one.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new TeamScope);
}
}
For example:
<?php
namespace App;
class Attribute extends BaseModel
{
}
You could also have a trait that you can just use to add this scope to your Model. For example:
trait HasTeamScope
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new TeamScope);
}
}
}
... and then you can easily re-use that in your Model.
For example:
<?php
namespace App;
class Attribute extends BaseModel
{
use HasTeamScope;
}
Now, based on your question, you might also forget to extend the BaseModel in the first instance or add the Trait in the second one whenever you create a new model.
To solve this, you could easily create a new command to produce models that will use your own stub (which extends the BaseModel or adds the trait whenever you create a new model)
You could create your own base model with the desired global scope that future models would extend.
You should create trait with boot function. Trait named BelongsToTeam.
And in all models add only: use BelongsToTeam;

laravel QueryException table not found

I am not getting it that why i am facing it.
I created a migration name 2018_01_12_035551_create_inquiry_master_table
In my route file assign a route Route::get('lists-inquiry','InquiryController#listinquiry')->name('lists-inquiry');
Created a controller name InquiryController
Controller code:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller as BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\InquiryMaster;
use Illuminate\Support\Facades\Input;
class InquiryController extends BaseController
{
public function listinquiry() {
$inquiry = InquiryMaster::all();
// dd($inquiry) Here i am getting error
return view('admin.list_inquiry')->with('listinquiry', $inquiry);
}
}
Created a model InquiryMaster
My model look like:
<?php
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class InquiryMaster extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'created_date_time',
'user_id',
'stitch_video_path',
'completion_status'
];
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
}
When i dd($inquiry) in controller it returns error
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'bigball_travel.inquiry_masters' doesn't exist (SQL: select * from inquiry_masters)
It shows table inquiry_masters
and i created inquiry_master
add protected $table = 'inquiry_master'; to InquiryMaster model
so class would look like this.
<?php
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class InquiryMaster extends Model
{
protected $table = 'inquiry_master';
protected $fillable = [
'created_date_time',
'user_id',
'stitch_video_path',
'completion_status'
];
}

Can not call Auth class inside Scope class in Laravel 5.2

I added External Scope for User Model. Simply created Scope, with the name DeveloperScope
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Auth;
class DeveloperScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
if(Auth::user()->id != 1){
$builder->where('id', '<>', 1);
}
}
}
Then, I called this scope for User model.
User Model
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Scopes\DeveloperScope;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use SoftDeletes;
use Authenticatable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['first_name', 'last_name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['deleted_at'];
protected static function boot()
{
parent::boot();
static::addGlobalScope(new DeveloperScope);
}
}
It works well, when I don't use Auth::class inside DeveloperScope class. The reason is that, I just want to hide the main user for another users for all Eloquent methods. Of course, I can use session instead of Auth and retrieve user id. But it is still interesting for me, why browser gives an error: ERR_EMPTY_RESPONSE while using Auth::class ?
The method what you are looking for is exactly Auth::hasUser(). The method was added in Laravel 5.6 through my PR. (So you need to upgrade Laravel first)
[5.6] Add ability to determine if the current user is ALREADY authenticated without triggering side effects by mpyw · Pull Request #24518 · laravel/framework
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class DeveloperScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
if (!Auth::hasUser() || Auth::user()->id != 1) {
$builder->where('id', '<>', 1);
}
}
}
Just call Auth::hasUser() to prevent Auth::user() from causing side effects.
Try injecting the Illuminate\Auth\Guard class and then call the user method on it. e.g.:
$this->auth->user();
You should be fine with just type-hinting it since Laravel will automatically new up an instance for you.
For more info check out the API: https://laravel.com/api/5.2/Illuminate/Auth/Guard.html

Resources