MorphMap is not working in Laravel 5.6 - laravel

I am using Polymorphic relationship in my models and with polymorphic relations I want to use Moprph map. To implement the concept of morph map I wrote my own service provider and registered it in app.php. Everything is working fine except Morph map. Morphmap is not working even with AppServiceProvider. Please have a look on my code
Service Provider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
class MorphServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
Relation::morphMap([
'First' => FirstModel::class,
'Second' => SecondModel::class,
'Third' => ThirdModel::class
]);
}
/**
* Register services.
*
* #return void
*/
public function register()
{
//
}
}

I ran into this situation too. Finally I solved this problem by running artisan command:
php artisan cache:clear
The Reason Why MorphMap is not working
The new custom service is not loaded. Check bootstrap/cache/services.php to see if the new ServiceProvider is in the array of providers
<?php return array (
'providers' =>
array (
0 => 'Illuminate\\Auth\\AuthServiceProvider',
1 => 'Illuminate\\Broadcasting\\BroadcastServiceProvider',
2 => 'Illuminate\\Bus\\BusServiceProvider',
3 => 'Illuminate\\Cache\\CacheServiceProvider',
4 => 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider',
5 => 'Illuminate\\Cookie\\CookieServiceProvider',
6 => 'Illuminate\\Database\\DatabaseServiceProvider',
7 => 'Illuminate\\Encryption\\EncryptionServiceProvider',
8 => 'Illuminate\\Filesystem\\FilesystemServiceProvider',
//...
By default this file should update automatically after the app.php has been altered.
In my situation, I accidentally ran the command php artisan config:cache before. This prevent the services.php from updating. Further Reference:
Laravel Doc: Configuration
Why caching config would prevent services.php from updating
check bootstrap/cache/config.php, look inside what's in there. providers is part of application config
check Illuminate\Foundation\Http\Kernel
protected $bootstrappers = [
\Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,
\Illuminate\Foundation\Bootstrap\LoadConfiguration::class,
\Illuminate\Foundation\Bootstrap\HandleExceptions::class,
\Illuminate\Foundation\Bootstrap\RegisterFacades::class,
\Illuminate\Foundation\Bootstrap\RegisterProviders::class,
\Illuminate\Foundation\Bootstrap\BootProviders::class,
];
check Illuminate\Foundation\Bootstrap\LoadConfiguration
check Illuminate\Foundation\Application, registerConfiguredProviders
Finally, I have to say that I am quite new to laravel. If I made some mistakes, let me know. Thank you.

Related

Laravel Cashier - Class "App\Models\User" not found

When trying to cancel a subscription with Laravel Cashier, it returns the error:
Class "App\Models\User" not found
Code:
public function cancel(Request $request) {
$subscription = Auth::user()->subscription('default');
$subscription->cancel();
}
This is likely because my user model is not located at "App\Models\User" (the new default in Laravel 8), but rather it is located at "App\User".
In the official documents, it mentions this:
If you're using a model other than Laravel's supplied App\Models\User model, you'll need to publish and alter the Cashier migrations provided to match your alternative model's table name.
But this isn't the problem. My table name is the same, but the location of my model is different.
How do I fix this?
use App\User; // this is important in your case
use Laravel\Cashier\Cashier;
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Cashier::useCustomerModel(User::class);
}
Docs: https://laravel.com/docs/8.x/billing#billable-model
Try change your providers config in config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
]
Reference https://laravel.com/docs/8.x/authentication#the-user-provider-contract

Is it possible to import excel data into laravel REST API?

I don't know how to import the excel data to my database via REST API in laravel, I try so much research on google but those tutorials and videos aren't related to API..... pls help
Download the dependecy using composer for Import and export excel file.
composer require maatwebsite/excel
Add providers and aliases in config/app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
......,
......,
Maatwebsite\Excel\ExcelServiceProvider::class,
]
'aliases' => [
.......,
-------,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
Now publish the changes using vendor:publish
php artisan vendor:publish
Make migration and migrate it using command.
Add routes
Create Import and Export class using import/export command
Note: This command avaialble only if you download dependecy successfully using composer(step 1)
In app/Imports/BulkImport.php file
<?php
namespace App\Imports;
use App\Bulk;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class BulkImport implements ToModel,WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Bulk([
'name' => $row['name'],//fields from excel
'email' => $row['email'],
]);
}
}
Make A controller and in controller use
Excel::import(new BulkImport,request()->file('file'));
Bulk is the model in this example
Hope it Will helps Have a Good Day

Getting class does not exist error when running database seeder

I am creating a seeder in laravel 6.1 but I keep getting this error
Illuminate\Contracts\Container\BindingResolutionException : Target class [AdminsTableSeeder] does not exist.
I tried running composer dump-autoload and composer dumpautoload, it doesn't work for me.
here is my AdminsTableSeeder.php
use App\Models\Admin;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
class AdminsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$faker = Faker::create();
Admin::create([
'name' => $faker->name,
'email' => 'admin#admin.com',
'password' => bcrypt('password'),
]);
}
}
and here is my DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(AdminsTableSeeder::class);
}
}
Make sure your AdminsTableSeeder.php file is in the same directory where you have your DatabaseSeeder.php file.
Run
composer dump-autoload
then try
php artisan db:seed
Optional.
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run(){
$this->call('AdminsTableSeeder');
}
}
try with $this->call('AdminsTableSeeder'); like this.
In your case, move all seeder files from previous database/seeds directory to database/seeders folder & then run composer dump-autoload.
Remember, from laravel 8 seeders and factories are namespaced
To accommodate for these changes,
[1] - Add Database\Seeders namespace to your seeder classes.
namespace Database\Seeders;
[2] - Move all seeder files to database/seeders folder.
[3] - If you import any seeders classes in DatabaseSeeder file then remove all of them. (simply remove all lines that started with use Database\Seeders\... from DatabaseSeeder.php)
[4] - Finally run dump-autoload.
composer dump-autoload
You can now try a fresh migration with seed,
php artisan migrate:fresh --seed
For my case(I use Laravel 8), I solved my problem by modifying the RouteServiceProvider.php file in App/Providers/ path. I uncommented code on line 29.
protected $namespace = 'App\\Http\\Controllers';
It worked for me.
run
composer dump-autoload
then try
php artisan db:seed
For Laravel 8:
I have the same issue and I found a solution in Laravel doc and it's worked for me.
https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces
Update Composer:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
}
Run:
composer dumpautoload
php artisan db:seed --force
Concerning my case, I used the latest Laravel 8 which is the latest version, I solved my problem by changing the RouteServiceProvider.php file in App/Providers/ path by uncommenting the code on line 29.
protected $namespace = 'App\Http\Controllers';
For Laravel ^7.0
If your using Laravel Eloquent
Example:
<?php
use App\Models\User;
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
public function run()
{
$users = [
[
'id' => 1,
'name' => 'Admin',
'email' => 'admin#admin.com',
'password' => bcrypt('password'),
'remember_token' => null,
],
];
User::insert($users);
}
}
If your using Laravel Query Builder
Example:
<?php
//Do not use -> namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
'name' => 'Admin',
'email' => 'admin#admin.com',
'password' => bcrypt('password'),
'remember_token' => null,
]);
}
}
In your DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
UsersTableSeeder::class,
]);
}
}
Seems like the controller name is case-sensitive in Laravel 8. So my suggestion is to double-check the controller name.
For instance:
in web.php avoid calling
UserAPIController
as
UserApiController
(API as api)
It may fix this error.
In your DatabaseSeeder.php, you can add the nameSpace for AdminsTableSeeder like -
use App\Models\Admin\AdminsTableSeeder;
Closing the current running serve before doing db:seeds

Best place to store an array in Laravel

I'm using Laravel 5.2 and my app has the need for select boxes with half-hourly times in various different views throughout.
Here's an example of how the array data looks:
[
'00:00' => '00:00',
'00:30' => '00:30',
'01:00' => '01:00',
/* ... etc ... */
'18:00' => '18:00',
'18:30' => '18:30',
'19:00' => '19:00',
/* ... etc ... */
]
Obviously I don't want to put this in each controller that calls each view, but I'm wondering what the best way of storing it would be. So far, I've thought of the following:
1) A helper function that returns the array
2) A config file in app/config that contains the array
3) A database model (seems excessive)
4) A function that generates the list each time (performance concern?)
Can anyone think of a better way or suggest which one of the ways above would be best and why?
I have found a very good solution to this on Laracasts at https://laracasts.com/series/build-project-flyer-with-me/episodes/5
Here are the steps:
1) Create a file app/Http/Utilities.php:
<?php
namespace App\Http\Utilities;
class Time
{
protected static $times = [
'00:00' => '00:00', '00:30' => '00:30', '01:00' => '01:00'
/** etc ... **/
'22:30' => '22:30', '23:00' => '23:00', '23:30' => '23:30'
];
public static function all()
{
return static::$times;
}
2) In the view, add the following at the top:
#inject ('times','App\Http\Utilities\Time')
3) $times::all() can now be used within the view wherever necessary.
You can use Form Macro with Laravel Collective Package
Laravel Collective: https://github.com/LaravelCollective/html
An awesome example you can find https://github.com/rappasoft/laravel-5-boilerplate
See App\Providers\MacroServiceProvider.php
From my understanding of the question, this would be a perfect situation for View Composers, as it seems like you have some data that has to be generated on multiple views and/or in multiple controller methods.
The way I go about doing this:
Start by running php artisan make:provider ComposerProvider in your terminal.
This is what that provider could look like:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
view()->composer(
[
'view_one'
'view_two'
], 'App\Http\ViewComposers\DashboardComposer'
);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
There you can list all the views that need this data.
An example of how a View Composer could look like. I place these in the folder app/Http/ViewComposers, as the namespace suggests.
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use Illuminate\Users\Repository as UserRepository;
class DashboardComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$the_variable = 'Hello World';
$data = [
'some_very_important_variable' => $the_variable
];
$view->with($data);
}
}

Laravel 4 DatabaseSeed.php throws class not found

I have tried so much to get this database seed to work but I still get Class 'Account' not found even though I have namespaced where I should.
There error is thrown when running php artisan db:seed on $accountOut = Account::create(array( where Account is what is throwing the error. Am stating the using incorrectly? If I were to remove all the namespacing I have no issues at all.
My Account.php file:
<?php namespace App\Models;
class Account extends \Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'account';
/**public function user()
{
return $this-belongsTo('User');
}*/
}
My seed file:
<?php
use App\Models;
class TransactionSeeder extends Seeder {
public function run()
{
DB::table('transaction')->delete();
DB::table('account')->delete();
$accountOut = Account::create(array(
'name' => 'Checking',
'origin' => 'Bank'
));
$accountIn = Account::create(array(
'name' => 'Stuff',
'origin' => 'Expense'
));
$adminUser = Sentry::getUserProvider()->findByLogin('admin#admin.com');
Transaction::create(array(
'account_id_in' => $accountIn->id,
'account_id_out' => $accountOut->id,
'amount' => 300.00
));
}
}
I feel really stupid but instead of calling out use App\Models you would call out use App\Models\Account and it works as it should.
Then remember to run php composer.phar dump-autoload
I've had similar issues and prefixing my classes with the namespace operator solved them.
Try \Account

Resources