Laravel Artisan Console Command Cannot Retrieve Model Collection - laravel-5

I am trying to do some logic via a custom Console Command I created using Artisan but I am unable to use my model class and query using Eloquent.
When I use MyModel::all() it will return all records in a collection. This is great except the model I am using has too many records to load all of them into memory.
I am trying to use
MyModel::where('id',$currentLoopId)->get();
This returns an empty collection :(
My Console Class is as follows:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\ProcessReferral;
use App\TargetUrl;
use App\Website;
class ProcessReferrals extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'process:referrals';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Process all outstanding records in process_referrals table';
protected $logArray = [];
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$this->info('Start Processing Referrals');
$process_referrals = ProcessReferral::all();
$referral_count = count($process_referrals);
$this->info('Found '.$referral_count.' referral(s) that need processed');
foreach($process_referrals as $referral){
## 1. SEE IF REFERRAL WEBSITE IS ACTIVE AND VERIFIED IN AFFILIATE_WEBSITES. LOAD LAST FORCE UPDATE REFRESH CODES
########################################
$this->info('Processing Referral ID: '.$referral->id);
$this->info('Get Website from Affiliate Website Id: '.$referral->affiliate_website_id);
$websites = Website::where('id','=',$referral->affiliate_website_id)->get();
dd($websites);
... ( more Logic after I get website )
}
}
My Model Class is as follows:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Website extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'affiliate_websites';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
...
];
... ( Eloquent Relations )
}
Database Table:
id website_label referrals
------------------------------
1 Google UK 920685
2 Google U.S. 2940884
3 Google Germany 709603
First Dummy Data Record being processed:
id affiliate_website_id
-------------------------
2 3
Output on Terminal
$ php artisan process:referrals
Start Processing Referrals
Found 300 referral(s) that need processed
Processing Referral ID: 2
Get Website from Affiliate Website Id: 3
Website(id->62) is Active.
Illuminate\Database\Eloquent\Collection {#901
#items: []
}
I have tried a handful of different ways to query including DB::select() which returns what I am looking for but I cannot dynamically set the id I am searching for with that convention.
My Model works everywhere else in my application, I think there is some sort of Namespacing issue coming into play but I am at a complete loss as to why it wouldn't work.
Any help would be very appreciated!

As pointed out by #machuga on http://laravel.io/chat
I checked to see if the ID i was passing was an integer
$website = Website::where('id',(int)$referral->affiliate_website_id)->first();
Still had some issues but used ->first() to get a single record instead of ->get() so I dont have to loop over the Website collection

Related

Edit Fields Not working; not updating, and sending empty array to backend

I am using Laravel version 9.41 and Nova 4.
I can delete records, however it appears that on the frontend/JavaScript side of things my form fields are not having their contents captured and sent back to the server. My action_events table shows [ ] empty arrays as what is being sent.
I have spent a good four or five hours googling and checking that my Resources, field names etc. are all spelled correctly. I also see no error messages. Each time I get the green success message, "This has been updated!" or whatever.
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
class Post extends Resource
{
/**
* The model the resource corresponds to.
*
* #var class-string<\App\Models\Post>
*/
public static $model = \App\Models\Post::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id',
'text'
];
/**
* Get the fields displayed by the resource.
*
* #param \Laravel\Nova\Http\Requests\NovaRequest $request
* #return array
*/
public function fields(NovaRequest $request)
{
return [
ID::make('id', 'id')->sortable(),
Text::make('text', 'text')->sortable()
];
}
Someone gave me the answer elsewhere: inn my Post model, after deleting/commenting out the lines in the screenshot below: all worked fine. There was no reason to define the following properties. They are not part of any Eloquent conversion. I did not need the following (in App/Models/Post):

Is possible in Laravel Nova 4 use a field of nested relation in search fields?

I have the following db:
Showcases (n to 1) Workers (1 to 1) Users
I need in the showcase resource section find showcase by user's name. In the Nova's documentation they explains that is possible search by related field like this:
public static $search = [
'id', 'author.name'
];
If I try 'worker.user.name' it doesn't works. Any idea?
You'll have to define it on your Laravel Model, otherwise it wont work.
use Laravel\Nova\Query\Search\SearchableRelation;
/**
* Get the searchable columns for the resource.
*
* #return array
*/
public static function searchableColumns()
{
return ['id', new SearchableRelation('author', 'name')];
}
You can use this package titasgailius/search-relations.
<?php
namespace App\Nova\Resources\OrderManagement;
use App\Nova\Resources\Resource;
use Titasgailius\SearchRelations\SearchesRelations;
class Showcase extends Resource
{
use SearchesRelations;
/**
* The relationship columns that should be searched.
*
* #var array
*/
public static $searchRelations = [
'worker.user' => ['name'],
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [];
}
}
*Assuming you have set the belongsTo relationships properly in your models.

What is the database password of a tenant's database (Laravel Hyn)

I have deployed a multi-tenant site on the server and I'm using Laravel Hyn (5.6). I am able to create tenant's database. But I wonder what is the password used to create the tenant's database. I'm asking this because if ever we need to check on a tenant's database, how can we access it? And I'm trying to access it remotely. I can get into the app's main database which holds the tenant's database name. But I don't know how to access the tenant's actual database because I don't know what password Hyn assigned to it.
Checking Laravel Hyn's docs, It doesnt mention anything about it.
The functionality you are looking for is in class Hyn\Tenancy\Generators\Database\DefaultPasswordGenerator function generate
Possibly if we can adapt this functionality to come up with a command that accepts the database name and returns the password. We can come up with something like this
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Hyn\Tenancy\Models\Website;
use Hyn\Tenancy\Contracts\Website as WebContract;
class GeneratePassword extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'password:generate {--database=}';
/** php artisan password:generate --database=6003c07826144979a4176b3290963ba3
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
$database=$this->option('database');
$website =Website::where('uuid', $database)->first();
$password=$this->generate($website);
$this->info('password :'.$password);
return 0;
}
/**
* #param Website $website
* #return string
*/
private function generate(WebContract $website) : string
{
$key = config('tenancy.key');
// Backward compatibility
if ($key === null) {
return md5(sprintf(
'%s.%d',
$this->app['config']->get('app.key'),
$website->id
));
}
return md5(sprintf(
'%d.%s.%s.%s',
$website->id,
$website->uuid,
$website->created_at,
$key
));
}
}
You will now be able to generate passwords via artisan console for example
php artisan password:generate --database=6003c07826144979a4176b3290963ba3
Use the generated password to connect to your database using tenant credentials (username is the same as database name).

Laravel Nova BelongsTo Field Appending Namespace To Current Namespace

I am currently using laravel 5.8 with laravel nova.
When i use a model class inside my nova action file, like this:
Namespace App\Nova\Actions;
use App\Nova\User;
use Orlyapps\NovaBelongsToDepend\NovaBelongsToDepend;
class PlayerDD extends Action
{
public $name = 'Spelers toekennen';
/**
* Perform the action on the given models.
*
* #param \Laravel\Nova\Fields\ActionFields $fields
* #param \Illuminate\Support\Collection $models
* #return mixed
*/
public function handle()
{
}
/**
* Get the fields available on the action.
*
* #return array
*/
public function fields()
{
return [
BelongsTo::make(User::class)
];
}
}
Laravel returns the error: Class 'App\Nova\Actions\App\Nova\User' not found.
While i am using the root namespace for the User model, the namespace gets appended to the current namespace.
Is there a fix for this, and where should i look for conflicts?
Thanks in advance!
BTW, i tried this \App\Nova\User

Not enough rights to add an object in Algolia Laravel

I have a problem with using Algolia. Working with database but i can't save it in to API Algolia.com. I tried to search through google but i didn't get any results for this problem.
My controller:
public function store(Request $request)
{
$role = new Role;
$role->name = $request->name;
$role->save();
}
My model:
<?php
namespace App;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use Searchable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
/**
* Get the index name for the model.
*
* #return string
*/
public function searchableAs()
{
return 'roles_index';
}
}
In you env file, make sure you are setting the admin key as the ALGOLIA_SECRET.
By default, Algolia gives you different key:
Search key, which can only perform search (read) operations.
Write key, which can index (write) data.
Admin key, which can do everything. This is the recommended one for Laravel Scout.
Please note that only the search key can be passed to your frontend, if you use Vue InstantSearch for instance.
Please let me know if that solved your issue.

Resources