Problems with migrations in Laravel 5.5 - laravel

Something really weird is going on with my Laravel setup. I create some migration files and, when running php artisan migrate after creating each of them, they were successfully run and the tables were created in the database. Now, if I want to run php artisan migrate:refresh --seed, it cannot rollback one of the migrations because it says that migration file doesn't exist.
This is the error:
And this is my migration file:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAssessmentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('assessments', function (Blueprint $table) {
$table->increments('id');
//TODO - Complete information for this table
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('assessments');
}
}
What's even weirder is that I had to re-create all migrations because it was randomly not creating some of the tables listed on the migrations.
Did anyone face this issue before? Any help is really appreciated.
[UPDATE]
After a while, I realized this is not something from Laravel. For some reason, my Homestead is not viewing those files despite there are there. If I access that folder via SSH (the one inside the vagrant box), the file is not there. If I go to the real folder, it is there. For some reason the box is not synching files properly.
What's even weirder is that I can access and edit the file inside the VMB but it won't list it and won't take into account when running migrations. Here I created a screen-recording showing the problem.
[UPDATE 2]
Just recorded 2 more videos. This is really strange (unless I am missing something).
Video 1.
Video 2.

It seems to be a problem with MacOS High Sierra and Vagrant. In order to fix it, I had to apply this workaround.
Hopefully this will save some time to the ones having the same problem I was having.

Related

Error when trying to view page, following error: Action Facade\Ignition\Http\Controllers\ShareReportController not defined

I am getting the error below when trying to access the route, but the controller is needed to load the data:
(1/1) InvalidArgumentException
Action Facade\Ignition\Http\Controllers\ShareReportController not defined.
I am using Tenancy/Multi-Tenant package and I have configured it to use routes/tenants.php to load routes specifically for tenants. If I do the following in the tenants.php file, it returns the proper response.
Route::get('/test', function() {
return 'Test success';
});
though when I try to do the same, but loading the data from a controller such as this:
Route::get('/testt', 'TenantController#testt');
It will show the error:
(1/1) InvalidArgumentException
Action Facade\Ignition\Http\Controllers\ShareReportController not defined.
If i try to put the same code in web.php routes, then it works perfectly. What could be the problem? Is it something in my code? Can it be because of the multi-tenant package i'm using? How would i go about further debugging this?
Can you see if your routes are cached and try clearing that cache. Just clear project route-cache using route:clear
The fix was to group the routes in tenants.php with the web middleware and a namespace:
Route::middleware('web')->namespace('App\Http\Controllers')->group(function() {
//Routes
});
Try composer dump-autoload -o
it helped for me.
After some minutes trying to fix I found the solution.
You don't need to group the routes if you've done in RoutesServiceProvider or in a custom Provider.
Just go to config/tenancy.php and go to routes -> path, Remove the base_path() function and let the string:
'path' => base_path('routes/tenants/tenants.php'),
to
'path' => 'routes/tenants/tenants.php',
And this error should be fixed.
I had a similar error after install laravel/passport 8.1 in Laravel 6.2:
Action Facade\Ignition\Http\Controllers\ExecuteSolutionController not defined.
Fixed it runnig composer update. The result was:
Updating facade/ignition (1.13.0 => 1.13.1):
For people finding this via Google: I had a similar error with Laravel 6.5. I had messed up my AppServiceProvider with an incomplete Git merge:
<?php
namespace App\Providers;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
<<<<<<< HEAD
Blade::if(
'iscurrentroute',
function ($route) {
$route = Str::replaceFirst(Request::getSchemeAndHttpHost().'/', '', $route);
return Request::is($route);
}
);
=======
Blade::component('components.sortable', 'sortable');
>>>>>>> feature/WLI-58-bedrijf-beheren
}
}
Deleting the "='s", "<'s", and ">'s", and the double use of Blade fixed it for me.
on server side I went to /stoage folder and cleared cashs. E.g. views folder inside that /storage. Then additionally changed all entire folders' and files' permissions to can read and write.
Then pages started show up as expected
I was using the Ignition error pages in Laravel and I have to say that I much prefer the whoops package.
I had the same error reported in this question and by chance changing the error package installed in my app to the whoops one showed me the real error my app was having and I was then instantly able to resolve it. So it seemed that ignition wasn't exactly the cause but it was hindering me resolving another issue.

Laravel app deployment in Heroku fails with handling the post-autoload-dump event returned with error code 1 [duplicate]

I have been using Eloquent as a standalone package in Slim Framework 2 successfully.
But now that I want to make use of Illuminate\Support\Facades\DB since I need to show some statistics by getting the info from 2 tables and using a Left Join and a Counter from the database like this:
use Illuminate\Support\Facades\DB;
$projectsbyarea = DB::table('projects AS p')
->select(DB::raw('DISTINCT a.area, COUNT(a.area) AS Quantity'))
->leftJoin('areas AS a','p.area_id','=','a.id')
->where('p.status','in_process')
->where('a.area','<>','NULL')
->orderBy('p.area_id');
I get the following error:
Type: RuntimeException
Message: A facade root has not been set.
File: ...\vendor\illuminate\support\Facades\Facade.php
Line: 206
How can I solve it?
So far I have found out, in this link that I need to create a new app container and then bind it to the Facade. But I haven't found out how to make it work.
This is how I started the rest of my Eloquent and working fine:
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule();
$capsule->addConnection([
'my' => $app->config->get('settings'),
/* more settings ...*/
]);
/*booting Eloquent*/
$capsule->bootEloquent();
How do I fix this?
Fixed
As #user5972059 said, I had to add $capsule->setAsGlobal();//This is important to make work the DB (Capsule) just above $capsule->bootEloquent();
Then, the query is executed like this:
use Illuminate\Database\Capsule\Manager as Capsule;
$projectsbyarea = Capsule::table('projects AS p')
->select(DB::raw('DISTINCT a.area, COUNT(a.area) AS Quantity'))
->leftJoin('areas AS a','p.area_id','=','a.id')
->where('p.status','in_process')
->where('a.area','<>','NULL')
->orderBy('p.area_id')
->get();
You have to change your code to:
$Capsule = new Capsule;
$Capsule->addConnection(config::get('database'));
$Capsule->setAsGlobal(); //this is important
$Capsule->bootEloquent();
And at the beginning of your class file you have to import:
use Illuminate\Database\Capsule\Manager as DB;
I have just solved this problem by uncommenting $app->withFacades(); in bootstrap/app.php
Had the same issue with laravel 8. I replaced
use PHPUnit\Framework\TestCase;
with:
use Tests\TestCase;
Try uncommenting in app.php $app->withFacades();
Do not forget to call parent::setUp(); before.
fails
public function setUp(): void {
Config::set('something', true);
}
works
public function setUp(): void {
parent::setUp();
Config::set('something', true);
}
One random problem using phpUnit tests for laravel is that the laravel facades have not been initialized when testing.
Instead of using the standard PHPUnit TestCase class
class MyTestClass extends PHPUnit\Framework\TestCase
one can use
class UserTest extends Illuminate\Foundation\Testing\TestCase
and this problem is solved.
I got this error after running:
$ php artisan config:cache
The solution for me was to delete the /bootstrap/cache/config.php file. I'm running Laravel 5.5.
The seems to arise in multiple situation, and not just about facades.
I received the following message while running tests using PHPUnit v.9.5.4, PHP v.8.0.3 and Lumen v. 8.2.2:
PHP Fatal error: Uncaught RuntimeException: A facade root has not
been set. in path_to_project/vendor/illuminate/support/Facades/Facade.php:258
And that happened although I had apparently already configured my app.php to enable facades ($app->withFacades();), still I received this error message whenever I tried to run tests using Illuminate\Support\Facades\DB. Unfortunately, none of the other answers helped me.
This error was actually been thrown due to my configs in phpunit.xml, which didn't point to my app.php file, where I actually enabled facades.
I just had to change
<phpunit (...OTHER_PARAMS_HERE) bootstrap="vendor/autoload.php">
to
<phpunit (...OTHER_PARAMS_HERE) bootstrap="bootstrap/app.php">
Hope it helps.
wrong way
public function register()
{
$this->app->bind('Activity', function($app)
{
new Activity;
});
}
right way 👍
public function register()
{
$this->app->bind('Activity', function($app)
{
return new Activity;
});
}
---------------------------------- don't forget return
Upgrade version for php, I encountered this error while calling the interface.
$ php artisan config:cache
Deleting the /bootstrap/cache/config.php file is a very effective way.
In my project, I managed to fix this issue by using Laravel Dependency Injection when instantiating the object. Previously I had it like this:
$class = new MyClass(
new Client(),
env('client_id', 'test'),
Config::get('myapp.client_secret')
);
The same error message happened when I used Laravel env() and Config().
I introduced the Client and env in the AppServiceProvider like this:
$this->app->bind(
MyClass::class,
function () {
return new MyClass(
new Client(),
env('client_id', 'test')),
Config::get('myapp.client_secret')
);
}
and then instantiated the class like this:
$class = app(MyClass::class);
See more from https://laravel.com/docs/5.8/container .
In my case, for a while a ran a PHP project in PHP version 8, and that time I used some PHP 8 features like param definition and method's multiple return type declarations supported by only PHP 8 and above. When I downgraded from PHP 8 to PHP 7.4 I faced this issue. After removing the return types and param hinting the problems are gone.
Tested on Laravel 8.78
tests/bootstrap.php
<?php
use Illuminate\Foundation\Bootstrap\RegisterFacades;
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
require_once __DIR__ . '/../vendor/autoload.php';
$app = require_once __DIR__ . '/../bootstrap/app.php';
(new LoadConfiguration())->bootstrap($app);// <------- Required for next line
(new RegisterFacades())->bootstrap($app);// <------- Add this line
Here is yet another instance of this error, happened to me after upgrading Laravel 8 to 9.
I had feature tests with a #dataProvider to supply data to those tests. Some of the data supplied by the data provider methods came from an application service. It was being initialised like this:
/**
* #dataProvider myDataProvider
*/
public function testSomeStuff(...)
{
...
}
public function myDataProvider()
{
$myService = app(Service::class); // This is trouble
return [
['test1_data' => $myService::SOME_CONSTANT],
[...],
...
];
}
This worked under Laravel 8, but not in Laravel 9. All other solutions listed in this SO thread were checked and were correctly set up.
The problem is that the application is not being inititialised until after the data provider method is run. It was presumably initialised before this stage in the Laravel 8 install. So app(Service::class) was failing due to it using facades internally.
One workaround could be to force the application to initialise earlier, in the data provider function: $this->createApplication(). I would not recommend this due to potential side effects of the test parts running in the wrong order, though it does appear to work when I tried it.
Best solution is to avoid accessing any part of the application functionality in the data provider methods. In my case it was easy to replace $myService::SOME_CONSTANT with MyService::SOME_CONSTANT after making sure those constants were public.
Hopefully this will help somebody suddenly hitting this problem running feature tests after a Laravel 9 upgrade.
If you recently upgrade Laravel on Homestead & VirtualBox environment or do not find any reason that causing please be sure your Vagrant is up to date.
Referance
I had Taylor lock this thread. The past several replies have restated the solution, which is to Upgrade to Virtualbox 6.x, the thread is locked to prevent other issues that are not related from being dogpiled on here.
#melvin's answer above works correctly.
In case someone is wondering about it, the mistake people do is to choose Yes when VSCode asks them if they are making a Unit Test. Remember, Unit Tests should really be unit tests, independent of other application features (models, factories, routes; basically anything that would require the Laravel app to be fired up). In most scenarios, people really actually want to make Feature Tests and therefore should answer No to the above question. A feature test inherits from Tests\TestCase class (which takes care of firing up Laravel app before running the test) unlike unit tests that inherit from the class PHPUnit\Framework\TestCase which use just PHPUnit and are therefore much faster.
credit with thanks to #Aken Roberts's answer here.
From Laravel Documentation: Generally, most of your tests should be feature tests. These types of tests provide the most confidence that your system as a whole is functioning as intended.

How to maintain two migration tables in Laravel Migration

I'm writing a custom migration and I need to maintain those migrations in a separate migration repository table. I override DatabaseMigrationRepository and replace the migration repository function as follows
public function registerRepository()
{
$this->app->bindShared('migration.repository', function($app)
{
$table = $app['config']['database.cf_custom_migrations'];
return new CustomDatabaseMigrationRepository($app['db'], $table);
});
}
And I have registered my custom migration in artisan.php.
But when I call the custom migration command its execution is based on the Default Migration command.
Have anyone tried this before? How can run the Custom Migration command on Custom Migration table?
create a custom command instead of using migrate which is default to laravel.
use that custom command to run your custom migrations.
hope it helps

Laravel 5.2 and Cashier

I have added:
"laravel/cashier": "^6.0"
to composer.json
and:
Laravel\Cashier\CashierServiceProvider::class,
to app.php in the providers array in the config folder.
I have then run composer update, but if I do:
php artisan
I do not see the cashier command there. Am I missing a step?
That command appears to be removed in 5.2. In looking at the docs for 5.2 they've been updated and there is no longer a reference to using the artisan helper `$php artisan cashier:table users
Rather is seems you must now create the migration manually rather than using a helper. From the docs:
Update the user table migration(or whichever entity you are associating with your billing):
Schema::table('users', function ($table) {
$table->string('stripe_id')->nullable();
$table->string('card_brand')->nullable();
$table->string('card_last_four')->nullable();
});
Create a subscriptions table:
Schema::create('subscriptions', function ($table) {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('stripe_id');
$table->string('stripe_plan');
$table->integer('quantity');
$table->timestamp('trial_ends_at')->nullable();
$table->timestamp('ends_at')->nullable();
$table->timestamps();
});
Then run the migrate command $ php artisan migrate
I wasn't able to find any info on the reason for this change or whether they'll be re-introducing this artisan command in the future. I assume it is by design though.
Click here for more info on creating migrations.
Hope it helps!

How to globally prevent saving to database in Laravel 5

I made a PHP script in Laravel and now I want to show demo to my buyers. Since I don't want them to make any changes to the database, I was wondering if there is a way to globally disable any saving to the database?
If you have a BaseModel that extends Laravel's default Eloquent model class. And all of your applications models extend that BaseModel you can add the following to it:
public static function boot()
{
parent::boot();
static::saving(function($model)
{
return false;
});
}
This will intercept any creating or updating events from Eloquent.
This may be the technical answer for your question, but ideally just backup your db and restore it after showing to your buyers.
The easiest thing will be to create a mysql user that hasn't permissions to insert. Use the following mysql statement to create the user and use this user as the user in your database setting. I don't think there's a global method for this in laravel.
GRANT SELECT ON [database name].[table name] TO ‘[username]’#'%’;
This way, your user can view everything, but isn't able to save a bit.

Resources