Handle Laravel 5.3 QueryException? - php

Laravel 5.3
I know what happens. In my boot function of AppServiceProvider I have code that shares data for all views:
$unread_messages = count(Message::where('status', 0)->get());
View::share('unread_messages', $unread_messages);
But, if there is no such a table ( after DB reset ), that throws an Exception
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'lara53.messages' doesn't
exist (SQL: select * from `messages` where `status` = 0)
[PDOException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'lara53.messages' doesn't
exist
If I comment that code in the boot function it is okay, and all php artisan commands are working fine.
I have tried the following:
try
{
$unread_messages = count(Message::where('status', 0)->get());
View::share('unread_messages', $unread_messages);
} catch (Exception $e)
{
$e->getMessage();
}
It throws same error. I've also tried this:
if (Schema::hasTable('messages')){
but then it shares nothing.
How do I handle this?

You can use view composer so your query is not executed instantly when provider is loaded. Instead register view composer, and query will be executed only when view actually needs it.
Read more: https://laravel.com/docs/5.2/views#view-composers

This isn't a good use of service providers, which are generally meant to bootstrap requirements of your app such as 3rd party packages. As you can see, placing queries to share data with views isn't efficient in a service provider because they are run on quite literally every single request (why should it need to run that query if you are just using the console?)
Instead, you should place this code into a middleware while considering if you should also take Robert TrzebiƄski's advice and put it in a view composer as well inside of that middleware.

Related

Lumen call to DB::connection() returns null even though select() is successful

I am using Lumen 5.3.1. $app->withFacades() and $app->withEloquent() have been uncommented in app.php. In web.php I run the following code:
$app->get('foo', function () {
return app('db')->select("SELECT * FROM foo");
return "Connected successfully to database " . DB::connection()->getDatabaseName();
});
The select() call correctly returns data from the foo table. However, DB::connection() returns:
FatalErrorException in Manager.php line 74:
Call to a member function getConnection() on null
Why does one work but not the other?
I'd say double check your service providers. It looks like you are going through the DB Capsule, when actually that's intended for use out of Laravel/Lumen. Anyway if you are in fact using the Capsule Manager, you probably have to register it in a boot method of the provider, not register.
Also, in order to find out more about what's going on, add this to your test code:
dd(app('db'), DB::getFacadeRoot());
Share the result if you want, this will give more information about the difference between the two methods.
app('db')->select("SELECT * FROM foo");
DB::connection()->getDatabaseName();
try
app('db')->connection()->getDatabaseName();
or
\DB::connection()->getDatabaseName();

yii2 - how to truncate a table from console

I have created a console command and I need to truncate a table.
Reading the Class reference: http://www.yiiframework.com/doc-2.0/yii-db-command.html#truncateTable()-detail I am not able to understand what files I need to include in order to execute this command.
I am including:
use yii\db\Command;
use yii\db\Connection;
but not sure which one is correct.
And I have tried to execute:
$command = Yii::$app->db->truncateTable('user');
which gives me the following error:
Exception 'yii\base\UnknownMethodException' with message 'Calling unknown method: yii\db\Connection::truncateTable()'
and:
Yii::$connection->createCommand()->truncateTable('user');
which gives me the following error:
PHP Fatal Error 'yii\base\ErrorException' with message 'Access to undeclared static property: Yii::$connection'
I really don't understand what I need to do.
Yii::$app->db->createCommand()->truncateTable('user')->execute();
Using yii2 migrate that default function
yii2 migrate
Step 1. Create a migrate
yii migrate/create truncate_table_xxx
Step2. Edit file xxx_truncate_table_xxx
Some thing like that
class m150101_185401_truncate_table_xxx extends Migration
{
$this->dropTable('xxx')
}
Alternatively one may use:
User::deleteAll();
assuming User is active model class.
This command shows the number of deleted records.
Note, that unlike truncate deleting all records will NOT reset autoincrement counter to 1.

PHP Artisan throwing strange error [42s02]

I'm getting a weird error trying to use PHP Artisan. I don't know the cause, or even which file is causing it.
Just a few moments ago I ran php artisan migrate:reset to wipeout all the tables in my db. Worked fine.
Then I made a change to a file completely unrelated to the "stages" table, and when I try to run php artisan migrate it throws an error saying:
SQLSTATE[42S02]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'stages'. (SQL: select * from [stages] where [stages].[deleted_at] is null order by [opord] asc)
It throws that error no matter what I try to do, even just typing php artisan causes that fatal error.
Also, if I manually add a table called "stages" to the DB, artisan doesn't fail immediately, it tries to migrate the tables, then fails when it gets to the stages table, and it says it failed because "stages" already exists.
I don't even understand why artisan is trying to perform a select statement when I'm just trying to migrate my tables; and I especially don't understand why it's happening when running the php artisan command alone.
EDIT:
I traced the problem to some code that I had added to app\Providers\AppServiceProvider
public function boot(){
View::share('nav_stages', Stage::opord()->get());
}
I found a SO question about how to check if a table exists and I'm currently trying to make this work:
public function boot(){
if (Schema::hasTable('stages'))
{
View::share('nav_stages', Stage::opord()->get());
}else{
View::share('nav_stages', null);
}
}
The problem was caused by a bit of code I had in AppServiceProvider.php In the code I was trying to query the DB for data required by the navigation menu used on the entire site (a master page, layout, partial view, etc).
I replaced
public function boot(){
View::share('nav_stages', Stage::opord()->get());
}
With
public function boot(){
if (Schema::hasTable('stages'))
{
View::share('nav_stages', Stage::opord()->get());
}else{
View::share('nav_stages', null);
}
}
And added
use Illuminate\Support\Facades\Schema;
at the top of the file

ZF2 Database table no instance returned

I am facing a problem with my database models in ZF2, I must have touch something in the application as I am sure it worked before.
Wondering if somebody can read out the problem by the follow error messages I've got.
If more error info is needed I can update this question with the stacks :)
Zend\ServiceManager\Exception\ServiceNotCreatedException
File:
/home/xxxxx/domains/xxxx.nl/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:909
Message:
An exception was raised while creating "Application\Model\CelebrityTable"; no instance returned
**Previous exceptions:**
Zend\Db\TableGateway\Exception\RuntimeException
File:
/home/xxxx/domains/xxxx/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php:105
Message:
This table object does not have a valid table set.
Well the exceptions says most of what you need to know.
File:
/home/xxxx/domains/xxxx/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php:105
Message:
This table object does not have a valid table set.
I went to Zend/Db/TableGateway/AbstractTableGateway.php:105 and the following piece of code is there;
if (!is_string($this->table) && !$this->table instanceof TableIdentifier && !is_array($this->table)) {
throw new Exception\RuntimeException('This table object does not have a valid table set.');
}
So your exceptions means. The $this->table is not a string, array or an instanceof Zend\Db\Sql\TableIdentifier
So you probably didn't set the table.
Now I never used the AbstractTableGateway so not sure how to use it in the right context. But I don't see a setTable, or something like a setOptions.
So unless you can show your implementation of your TableGateWay, this is as far as I know.
Note, I looked at zf2.3.3

500 server error when saving Symfony entity

I need to couple my application with its database. To do this, I've generated an entity with doctrine:generate:entity. It's produced an entity with appropriate annotations for mapping. I've also used doctrine:schema:update --force to actually create the schema on the database server, which I can confirm it has done with phpMyAdmin.
In my controller I'm trying to simply insert a row like so:
public function testAction() {
$file = new File();
$file->setTest('A Foo Bar');
$em = $this->getDoctrine()->getManager();
$em->persist($file);
$em->flush();
return new JsonResponse(array('foo' => 'bar'));
}
The entity only has one field called test which is string and of length 255. When I request this URL through an AJAX request in my application, it throws back a very uninformative 500 Internal Server Error:
Oops! An Error Occurred
The server returned a "500 Internal Server Error".
Something is broken. Please e-mail us at [email] and let us know what you were doing when this error occurred. We will fix it as soon
as possible. Sorry for any inconvenience caused.
The PHP error logs also don't have any error information. This controller action does work if I remove the database manipulation stuff. The application is also running in the dev environment.
Is there any way I can get a more descriptive error message to at least tell me what's wrong?
This is a default error page that you get in production. You can customize it - http://symfony.com/doc/current/cookbook/controller/error_pages.html
You can catch and read an error creating ExceptionListener - http://symfony.com/doc/current/cookbook/event_dispatcher/event_listener.html
Also you can switch to dev environment to show error text and log.
If you just want dev logs but prod environment, you can copy contents of monolog section app/config/config_dev.yml to app/config/config_prod.yml.
If anyone here comes across this issue and is lost, the cause in my case was that I had specified a new #ORM\ManyToOne relationship and was persisting instead of merging the entity.
This in the past has returned a valid error, but in this case the php script was not handling it at all.

Categories