laravel user model not loading - laravel

I am doing a simple registration and login in laravel. I had previously built one taking laravel for a test drive prior to deciding to switch from CI. Anyway, the first time everything worked great. Upon reinstalling laravel, my User model does not seem to be loading. I can access User::method() for any properties or methods accessible in the Eloquent base model, but I cannot access any methods or properties declared static in my models/User.php model.
When I try and access a property I get "Access to undeclared static property"
I also tried to set a custom db table name for the users table and the system was not seeing this either. Not sure why it is loading, and not exactly sure how to check.
The User class is as follows:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public static $rules = array(
'first_name'=>'required|alpha|min:2',
'last_name'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
/* All other code in this is the standard code. */
}
The route is as follows
Route::get('create', function(){
//include(app_path().'/models/User.php');
print_r(User::$rules);
});
If I leave the comments in I get "Access to undeclared static property: User::$rules"
If I take the comments out I get a the anticipated print.

probably need to run php artisan dump-autoload from the command line

Related

One To Many Polymorphic relationship - Call to undefined method getConnectionName()

I have followed the documentation very closely but something isn't working
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-polymorphic-relations
I am trying to add permissions into my code which will give a User access to a File or a Folder. I understand this needs a one-to-many polymorphic relationship as each Permission has one permissionable, while each File or Folder might have many permissions.
$table->morphs('permissionable'); in a migration adds the permissionable_type(string) and permissionable_id(integer) columns to the permissions table
The Permission model has been created with the relevant fillable columns and the permissionable method containing a morphTo():
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\File;
class Permission extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'user_id',
'permissionable_type',
'permissionable_id',
'privilege',
];
/**
* Get the parent object (file or folder).
*/
public function permissionable()
{
return $this->morphTo();
}
}
The Folder and File models have both had the following methods added:
public function permissions()
{
return $this->morphMany(Permission::class, 'permissionable');
}
A Permission is going to be created which will share a File with a User
And then the Permission is found and it's permissionable is requested
dd(Permission::find(1)->permissionable);
Except this is where the area happens:
I have tried to follow the documentation religiously and all the answers I see online just say to check namespace or ensure that all Models have an extends Model which I have already done.
Let me know if there is any more information I need to provide, thanks in advance.
i think you just changes model File class name, it's ok.
because this model's name conflict with Facades File class name
Thanks to Noah and Erik for their answers. You both helped me find the solution which was on the following site.
https://laracasts.com/discuss/channels/general-discussion/polymorphic-relations-gives-class-staff-not-found
The types need to include the paths in the database

Laravel - How to pass cached value to multiple views without extra requests?

Have several data collections that are retrieved from cache and need to be passed to several different views.
For performance optimization need them to be retrieved only once, without extra requests to cache.
So using ViewComposer is not an option - it fires request to cache for each listed view.
Using following solution in AppServiceProvider :
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
view()->share('somedata', Cache::get('somekey'));
}
But in this case data passed to all views, which is not good from perspective of memory consumption.
Need ability to pass data only to certain views. (not pages, as those views are used on almost every page)
Something like following:
view(['viewname1', 'viewname2'])->share('somedata', Cache::get('somekey'));
You can use a View Composer. Example below taken from documentation.
Register the view composer in your AppServiceProvider and specify the routes it should be attached to;
View::composer(
['profile', 'dashboard'], // the routes you want to share it with
'App\Http\View\Composers\MyViewComposer' // your registered view composer
);
In your View Composer, get your cached variable and pass it to the views;
public function compose(View $view)
{
$someData = Cache::get('somekey');
$view->with($someData);
}

Laravel Authentication using different model rather than the user model

All about laravel authentication is based on users, but I have deleted the user model and replaced that with a company model, so, basically, I want my users (laravel authentication users) to be companies.
Laravel doesn't like this, it gives me
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\company given, called in /home/dhiraj1site/Desktop/Documents/blog/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.p
This error, and if I import authenticable class as suggested in similar questions. Laravel hates this and gives me a blank page.
I have companies model and a companies table, I want the users to sign up as companies, and login as companies. How should I go about this, I am really confused and stuck on this stage, please help me understand how authentication works (I have read authentication documentation several times) and how should I change 'Users' to 'companies'.
There are a couple of ways to skin this cat zuif. The 'Laravel' way would be to edit the settings in app/config/auth.php
In that file you'll need to change the line: 'model' => 'App\User' to 'model' => 'App\Company'.
The 'gotcha' with Laravel is that you must remember to implement the right interfaces in your new 'user' class, Company:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Company extends \Eloquent implements UserInterface, RemindableInterface
{
...
}
Or for newer versions of Laravel, its' just one interface:
use Illuminate\Foundation\Auth\User as Authenticatable;
class Company extends Authenticatable
I've done this before and it worked well for me. You could also get creative with extending the User class, but I think above is what you are hunting for.
HTH

Composer package - use custom model if exists

My apologies if this exists already but my search-fu can not find the answer.
I have a composer package, and want to use my model ONLY IF an existing model doesn't exist (or extend the custom model), but I can't seem to figure out how to specify the "use" command properly inside my composer model. Since I won't know the name of the "app" using the package, I can't extend it.
<?php
namespace MyComposer\Package\Models;
use Illuminate\Database\Eloquent\Model;
class MyPackageModel extends Model
{
If I put it as a config option, I can't use that in the extends i.e class MyPackageModel extends config('custom_model_name')
I had thought I should do the check in the ServiceProvider but I can't seem to find the right code to register the proper model name to use in there.
Thanks.
I've done something similar to this before, I believe. But my approach was slightly different. See if it makes sense:
Create a base class in your own package. This will be the fallback
model which will be used if the "local" package (the one consuming
your package) doesn't have it's own version of it;
Create a config file which states which model will be used. The default is the model inside your own package (i.e. the fallback);
After installing and setting up your package, if a user does nothing they will automatically have your base model available. If they wish to override your base model with a custom local version, they can simply extend your base model and alter the model to be used in their config file.
I've also found that sometimes it's useful for the base model to 1) implement an interface that can be checked in your package's logic without relying on a specific class (which, after all, is meant to be overridden, right?); and 2) have most of it's logic inside a trait which the "local" model can use without ever having to extend your model (crucial if the local model already extends some other class for whatever reason).
How you approach the code would very much depend what you plan to do with that model. Say, for example, you have a supporting class that creates media entries in your database. Here's your packages model:
<?php
namespace Namespace\Package;
class Media
{
//...
}
And here's the default config:
<?php
return [
'model' => \Namespace\Package\Media::class,
];
And here's a sample manipulation, where you actually account for the local app to override your own model:
<?php
namespace Namespace\Package;
class MediaManager
{
protected function getModel()
{
$model = config('package.model');
return new $model;
}
public function createMedia($attributes = [])
{
$media = $this->getModel($attributes);
$media->save();
return $media;
}
}
That is to say, you never reference any Media model literally. You do your manipulations via the MediaManager. Of course the logic is very simplistic, but hopefully it's enough to get the bigger picture.

Why does code igniter not segregate class types?

When you are using code igniter you load a library or model like so
$this->load->library('mylibrary');
$this->load->model('mymodel');
So, in a real world example, lets say you have a controller called user.
So, to login a user you send them to http://example.com/user/login
Now the login function loads a form that submits to http://example.com/user/login_do
You do some simple checks, and then send it over to your model to do the database check for you.
So you call
$this->load->model('user');
if($this->user->validate($email, $pass)){...}
UH OH!
Fatal error: Cannot redeclare class
User in
/var/www/unity/src/application/models/User_Model.php
on line ...
So what happened? Well, Code igniter does not segregate the classes, so your model now conflicts with your controller,
sure you can use
$this->load->model('user_model', '', 'user_m');
if($this->user_m->validate($email, $pass)){...}
So, Onto my question.
Why does code igniter not segregate the classes,
e.g. so you would call
$this->load->model('user');
if($this->model->user->validate($email, $pass)){...}
Sure it's slightly longer, but hell it would make things heaps nicer to user.
is it possible to extend code igniter so it works in this way?
It's not exactly the solution you're asking for (or a great idea), but there's nothing stopping you from doing this:
class Users extends CI_Controller {
private $model;
private $m;
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
$this->model->users = $this->user_model;
$this->m = $this->user_model;
}
function index()
{
// Here's that syntax you wanted
$this->model->users->get_many();
// Even shorter
$this->m->get_many();
}
}
You can really just assign anything to any property of the controller you want, as long as it's not the name of a loaded class or property (session, router, etc.). It can save you some typing if your model names are really long, but otherwise it's pointless and may conflict with things in the future.
Here's what I do if I'm not using *_model for model names:
Controller name: Users (plural)
Model name: User (singular)
No conflict, short syntax, sensible naming, it just doesn't work for some names like "news".
As I mentioned, it would be nice to see controller names using something like Controller_User or User_Controller to clear up the namespace issues a bit for the classes that we actually do have to call frequently, like models and libraries, but keep our urls as normal. I'm sure it can be done, something for a rainy day...
You missing the main point, PHP doesn't allow two classes with the same name, basically that's what Cannot redeclare class User says.

Resources