Using different namespaces models for Resources in Laravel 5.5 - laravel

love the Resources function in Laravel 5.5 which creates at resource prettier for a Model, but I have all my models stored in /App/Models/* instead of directly in the App/*-folder.
This is causing the App/Http/Resources/* not to work.
Results in a "Undefined property: Illuminate\Database\Query\Builder::$map"
This is caused because I stored my Models in a different folder which he can't map to by guessing.
Where and how to define the different placing of the Model?

For what I understand of your problem you have to inject the Model instance in the resource constructor, there is no magical autobinding, i.e.:
use App\Models\User;
use App\Http\Resources\User as UserResource;
Route::get('/user', function () {
return new UserResource(User::find(1));
});
I dont see any problem here, even with namespaced Models.

Not sure of the process you used to move the models to the new Models directory, so check a few things:
Namespace of the models
Each model has:
namespace App\Models;
Check references in these files
app/Http/Controllers/Auth/RegisterController.php
config/auth.php
config/services.php
database/factories/ModelFactory.php
Your Controllers
And change App/ModelExample to App/Models/ModelExample
Update autoload classmap
Add "app/models" to composer.json's classmap autoload section
"autoload": {
"classmap": [
"database",
"app/models"
]
}
Autoload files
Run composer dump-autoload

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

Why laravel helpers accessible from all namespaces?

So far i see that there are two file with functions that loaded with composer autoloader.
"autoload": {
"files": [
"src/Illuminate/Foundation/helpers.php",
"src/Illuminate/Support/helpers.php"
],
And then in autoloader:
function composerRequire69685de7f834ebe45f1e02416f8679f0($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
But actually it just require this file, and all functions comes only to global namespace. Can you explain me why eventually all this functions are accessible from all namespaces?
This is why helpers works in all namespaces:
For functions and constants, PHP will fall back to global functions
or constants if a namespaced function or constant does not exist.
PHP docs
It is because of composers psr-4 autoloading feature.
in the files section of composers autoload you are defining the files it should autoload. So let's consider in one of the files you have function called "calculate". When you now call calculate composer knows in which files it finds the function. If you would remove the files from the autoloading the function call would stop working.

How create own class helper in Laravel?

I need to create own class with methods, that I want to call from diverse controllers.
What it should be: Library, Provider or Helper in Laravel?
1: Create folder app/Helpers
2: In app/Providers create new provider file HelperServiceProvider.php
3: In this file register all helpers classes you need
$this->app->bind('dateHelper', function()
{
return new \App\Helpers\DateHelper;
});
... etc
4: In config/app.php add this new provider
'App\Providers\HelperServiceProvider',
5: Then you need to create Facade to be available to use this helper in view. You find the info about how to create Facade on official laravel.com site
About the providers, you can read the doc
Source: Laravel Forums
You can do this in many ways
Static way
Create a folder your wish Utils or Helpers or Libraries.
Create a Class (ex: Helper Class)
Added static methods here (ex: public static common()).
Added namespace to the call.
Use the name space and call the static function using(Helper::common)
Normal Class
Create class with name space.
Inject the Dependency of that class and use all function inside.
You can follow the simple steps below
Step 1
Create new helper file in app/Helpers directory
Ex. I have created the DemoHelper.php in directory app/Helpers/DemoHelper.php
Step 2
Add the entry of created Helper(DemoHelper.php) to composer.json file in autoload section
"autoload": {
"files": [
"app/Helpers/Helper.php",
"app/Helpers/DemoHelper.php"
]
},
Step 3
Finaly, composer dump-autoload hit this command in terminal.

Class App/Http/Controllers/View Not Found error

I am new to laravel 5 and currently stumped by this error:
FatalErrorException in TicketController.php line 18: Class 'App\Http\Controllers\View' not found
Weird thing is the view does in fact exist, i checked to see if the route was indeed routing to the right controller and it was, the error pops up when i try to do this:
return View::make('tickets.bus.index');
It's either i am making some mistake somewhere or if the implementation is different from laravel 4
The problem is not the actual view but the class View. You see when you just reference a class like View::make('tickets.bus.index') PHP searches for the class in your current namespace.
In this case that's App\Http\Controllers. However the View class obviously doesn't exists in your namespace for controllers but rather in the Laravel framework namespace. It has also an alias that's in the global namespace.
You can either reference the alias in the root namespace by prepending a backslash:
return \View::make('tickets.bus.index');
Or add an import statement at the top:
use View;
In Laravel 5.1 the correct use code would be:
use Illuminate\Support\Facades\View;
There exists a helper-function, view(), which is in the global namespace, and may be used to simplify the syntax:
return view('tickets.bus.index');
With this method, it is unnecessary to include use View; or include the root namespace, e.g., \View.
The concepts that lukasgeiter explained are essential to understanding Laravel, even if you elect to use the helper-function.
For me it was namespace problem. I used php artisan to create controller but it seems like php artisan used different namespace (may be I have to change something in composer.json to fix it but I am totally new in laravel)
Whoops, looks like something went wrong.
FatalErrorException in PagesController.php line 11:
Class 'App\Http\Controllers\Controller' not found
Good that I am using phpStorm which automatically inserted proper namespace
make sure you check out namespace properly. This is how I had controller created with php artisan
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller; //php artisan inserted.
class PagesController extends Controller
{
public function index(){
return view('index');
}
public function about(){
return view('pages.about');
}
}
and this is how phpstorm inserted after I manually wrote extends controller
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Routing\Controller; //I manually wrote extends Controller and selected this namespace
class PagesController extends Controller
{
public function index(){
...
There exists a helper-function, view(), which is in the global namespace, and may be used to simplify the syntax:
return view('tickets.bus.index');
With this method, it is unnecessary to include use View; or include the root namespace, e.g., \View.
The concepts that lukasgeiter explained are essential to understanding Laravel, even if you elect to use the helper-function.

Laravel model containing multiple classes

I'm new to laravel, coming from Codeigntier. I am trying to get to grips with the model/classes/eloquent convention that Laravel uses. I know that I can make a table in my database called, say, "categories". Then I can make a file in my models folder called category.php containing just the following code:
Class Category extends Eloquent { }
which automatically connects with the table name with the plural version of the name ("categories") and gives me access to all the Eloquent commands in my controller like Category::All();
Here's what I don't get: Do I need to make a new model for every table in my database? In that case I will end up with a bunch of files in my models folder with names like resource1.php, resource2.php, etc, each just containing the same code as above (replacing the name of the class).
Can't I just make one model called, say, "database_handler.php" and then just put all these classes into it in the same place?
Yes, you can create a database_handler.php file and do:
<?php
Class Category extends Eloquent { }
Class Post extends Eloquent { }
Class Client extends Eloquent { }
You can do whatever PHP let's you do, and add many classes to a single .php file is something you can do. But this is not a good practice and Laravel is all about developing application using the best ones.
To load this file automatically, you can do one of many things:
1) Add this file to your app/models folder.
2) Add an entry for it on your composer.json:
"autoload": {
"files": [
"app/database_handler.php"
]
},
And then you'll have to
composer dump-autoload -o
3) Create a different folder for it and also add it to composer json autoload section.
You choose, Laravel will let you free to do whatever you want.

Resources