Laravel 8 Docker - Many to Many Relationship not working - docker

I need a little help understanding why my many to many relationship is not functioning. I have spent the last 1/2 day going down many rabbit holes, from trying to change the php.ini file so i would not get an xdebug error (you will see below), trying to install vim on the docker container so I could edit the php.ini, spelunking why migrations were not working ......
i installed laravel 8 using docker. I am not sure but I wonder if my problems are due to a message I am getting when I try to run anything with artisan tinker:
Xdebug: [Step Debug] Could not connect to debugging client. Tried: localhost:9003 (fallback through xdebug.client_host/xdebug.client_port) :-(
I am able to run most artisan commands, but it fails to make a migration. If i type sail php artisan make:model [tablename] -m to try to make a migration at the same time, the system successfully makes a model, but it does not make a migration. sail php artisan make migration and sail php artisan migrate also return this xdebug error along with the ERROR: 255 code.
nonetheless (whatever the hec than means), I created the tables manually, and used the artisan make:model to make the models.
I have installed laravel breeze so my User Model looks like the following. I have cut some of the interior of the class out to save space.
thank you in advance for your help.
btw, you will notice there is a return type declaration for each of the models shown below. Those are there because php storm warned me with "missing function's return type declaration.'. So I chose to add the return type declaration. I tried this same code without the return type declaration, and received the same non-results.
this is the user model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use SoftDeletes;
/* i have deleted some methods, etc. here */
public function people(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(Person::class, 'user_person', 'user_id', 'person_id')->withTimestamps();
}
public function family(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(UserPerson::class);
}
}
this is the person model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Person extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'people';
public function users(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
return $this->belongsToMany(User::class, 'user_person', 'person_id', 'user_id')->withTimestamps();
}
}
This is the user_person model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserPerson extends Model
{
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}
}
this shows the error in php artisan tinker.
robertbryandavis#Roberts-iMac ~/D/s/rec4life (main)> sail php artisan tinker
Xdebug: [Step Debug] Could not connect to debugging client. Tried: localhost:9003 (fallback through xdebug.client_host/xdebug.client_port) :-(
Psy Shell v0.10.6 (PHP 8.0.2 — cli) by Justin Hileman
>>> $user = App\Models\User::where('email','bdavis#xxxxx.com')->get();
=> Illuminate\Database\Eloquent\Collection {#4381
all: [
App\Models\User {#4370
id: 7655,
name: "bob davis",
firstname: "bob",
lastname: "davis",
fields: taken out here for brevity
deleted_at: null,
created_at: "2019-02-07 13:43:05",
updated_at: "2021-03-18 23:56:44",
},
],
}
>>> $user->people()->get();
BadMethodCallException with message 'Method Illuminate\Database\Eloquent\Collection::people does not exist.'
>>> $user->people;
Exception with message 'Property [people] does not exist on this collection instance.'
>>> $user->family();
BadMethodCallException with message 'Method Illuminate\Database\Eloquent\Collection::family does not exist.'
>>> $user->family()->get();
BadMethodCallException with message 'Method Illuminate\Database\Eloquent\Collection::family does not exist.'
>>>

I am not sure if this is your case but I'm gonna tell you how I solved this issue, and got rid of that warning:
I solved it pointing my PHP error_log to a valid location by adding this line to my php.ini (in /etc/php/7.4/cli/php.ini):
error_log = /var/www/log/php_error.log
Change that location to any valid directory you want and try again. The warning should disappear from your output and now goes to the log file.

Related

hhvm issues \nFatal error: Uncaught Error: unknown class xhp_x__element in :\nStack trace:\n#0 /Users/user/code/xhp-js-example/example.php(12)

I'm trying to play with xhp and I'm finding that running the one xhp example I could find https://github.com/hhvm/xhp-js-example is issuing an error \nFatal error: Uncaught Error: Found top-level code in :\nStack trace:\n#0 {main} when following the README as is on HHVM 4.71. Removing require_once(__DIR__.'/vendor/autoload.php'); resolves the top-level code error but I'm now stuck with the error \nFatal error: Uncaught Error: unknown class xhp_x__element in :\nStack trace:\n#0 /Users/user/code/xhp-js-example/example.php(12): <unknown>()\n#1 {main}. I've tried to change the code in example.php to the one found here:
class :introduction extends :x:element {
protected function render(): \XHPRoot {
return <strong>Hello!</strong>;
}
}
class :intro-plain-str extends :x:element {
protected function render(): \XHPRoot {
// Since this function returns an XHPRoot, if you want to return a primitive
// like a string, wrap it around <x:frag>
return <x:frag>Hello!</x:frag>;
}
}
echo <introduction />;
echo PHP_EOL.PHP_EOL;
echo <intro-plain-str />;
since that didn't work, I also tried the simple example from here:
<?hh // strict
$user_name = 'Fred';
echo <tt>Hello <strong>{$user_name}</strong></tt>;
but altered to resolve the top-level error by wrapping it in a function and annotating it as follows:
<?hh // strict
<<__EntryPoint>>
function main(): void {
$user_name = 'Fred';
echo <tt>Hello <strong>{$user_name}</strong></tt>;
}
I'd get a very similar error \nFatal error: Uncaught Error: Class undefined: xhp_tt in /Users/user/code/xhp-js-example/example.php:6\nStack trace:\n#0 (): main()\n#1 {main}
Any help with getting these seemingly simple examples to work would be much appreciated since it's very painful and discouraging for trying this tech when the basic examples don't seem to run. this is using the macos package of hhvm on Catalina.
EDIT: I've also tried this without the use of xhp-js, which is included in the example repo and am getting the same error message.
There are a few roadblocks that the OP encountered to get XHP running with HHVM 4.62, as discussed in the comments.
xhp-js and xhp-js-example are both outdated by a few years so they can't compile due to breaking changes to HHVM itself, as the OP saw.
While the XHP syntax is built into Hack, all the standard implementations are provided by xhp-lib, so it is necessary to autoload that in order to use the standard library of tags and tag classes.
New to HHVM 4.62 is mandatory FIXME whitelisting, which requires package writers to explicitly specify allowed HH_FIXME codes in the .hhconfig. These were added to XHP-lib in 4.0.0rc1, so this version is necessary when running on HHVM 4.62.
Therefore, a minimal project with XHP on 4.62 looks like this:
composer.json
{
"require": {
"hhvm": "~4.62",
"hhvm/hhvm-autoload": "^3.1.3",
"facebook/xhp-lib": "~4.0.0rc1"
}
}
hh_autoload.json
{ "roots": [ "src/" ] }
src/example.hack
require_once(__DIR__ . "/../vendor/hh_autoload.hh");
<<__EntryPoint>>
function main(): void {
echo <div>{1 + 2}</div>;
}

Running init script on oracle test container with system privileges

I am struggling with org.testcontainers:oracle-xe:1.14.3.
I am trying to run a test intended to verify schema creation and migration, however I'm getting stuck at the InitScript, when trying to initialize the users for the test with the users 'sys as sysdba'.
#Before
public void setUp() {
oracleContainer = new OracleContainer("oracleinanutshell/oracle-xe-11g")
.withUsername("sys as sysdba")
.withInitScript("oracle-initscript.sql");
oracleContainer.start();
}
The above seems to be able to connect, but execution of the init script fails with a
ORA-01109: database not open
Using the 'system' user in the above does not provide the InitScript connection with sysdba privileges, but result in an open database.
I'm looking for a solution that will allow me to initialize multiple users prior to a test. This initialization has grants that requires sysdba privileges. The test, in which some SQL scripts are executed, requires that both users are created in the database and can connect to the database.
In my case I'm using
oracleContainer = new OracleContainer("gvenzl/oracle-xe:18.4.0-slim")
.withUsername("test")
.withPassword("test")
.addEnv("ORACLE_PASSWORD", "s") // Sys password is required
.withCopyFileToContainer(MountableFile.forHostPath("oracle-initscript.sql"), "/container-entrypoint-initdb.d/init.sql")
gvenzl/oracle-xe is the default image used by the org.testcontainers.oracle-xe library.
The documentation for this image describes how to call initialization SQL on DB start and it works great.
Hard to say what is the issue but here are some tricks:
maybe "sys as sysdba" is not valid in your code, documentation is not clear about the usage
maybe withLogConsumer can provide some clues what's wrong
I recommend the image gvenzl/oracle-xe,
in some cases withInitScript may not work properly.
it is useful to test the init script on the container started manually
I finished on end with this approach:
as sys admin created two different schema/user)
#SpringBootTest(classes = Main.class)
#Import(DbConfiguration.class)
#Testcontainers
public class ServiceIntegrationTest {
#Container
public static final OracleContainer oracleContainer =
new OracleContainer("gvenzl/oracle-xe:21-slim-faststart");
}
import static com.integrationtests.local_test.service.IntegrationTest.oracleContainer;
#TestConfiguration
public class DbConfiguration {
static final String DEFAULT_SYS_USER = "sys as sysdba";
private static final String ENTITY_MANAGER_FACTORY = "entityManagerFactory";
#Bean
public DataSource getDataSource() {
DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("oracle.jdbc.OracleDriver");
dataSourceBuilder.url(oracleContainer.getJdbcUrl());
dataSourceBuilder.username(DEFAULT_SYS_USER);
dataSourceBuilder.password(oracleContainer.getPassword());
return dataSourceBuilder.build();
}
Also in application.yaml put scripts
spring:
datasource:
initialization-mode: always
schema:
- classpath:/sql/init_schemas/USER_ONE.sql
- classpath:/sql/init_schemas/USER_TWOT.sql

Relay Compiler cannot compile Graph.Cool GraphQL schemas with multiple inheritance

I am using a generated schema from Graph.Cool that has the User type implementing two interfaces: Node and AnonymousUser. This looks like standard multiple inheritance. The Relay Compiler rejects this, however if I use an ampersand it works (implements Node & AnonymousUser vs. implements Node, AnonymousUser) and I'm not sure why. Anyone have some background on the correct syntax, or if this sounds like a bug?
COMPILER ERROR OUTPUT:
$ relay-compiler --src ./src --schema ./env/schema.graphql Error:
Error loading schema. Expected the schema to be a .graphql or a .json
file, describing your GraphQL server's API. Error detail:
GraphQLError: Syntax Error: Unexpected Name "AnonymousUser"
at syntaxError (/Users/kieran/Git/integer.systems/node_modules/graphql/error/syntaxError.js:24:10)
at unexpected (/Users/kieran/Git/integer.systems/node_modules/graphql/language/parser.js:1322:33)
at parseDefinition (/Users/kieran/Git/integer.systems/node_modules/graphql/language/parser.js:152:9)
at parseDocument (/Users/kieran/Git/integer.systems/node_modules/graphql/language/parser.js:110:22)
at parse (/Users/kieran/Git/integer.systems/node_modules/graphql/language/parser.js:38:10)
at getSchema (/Users/kieran/Git/integer.systems/node_modules/relay-compiler/bin/relay-compiler:260:28)
at /Users/kieran/Git/integer.systems/node_modules/relay-compiler/bin/relay-compiler:103:19
at Generator.next ()
at step (/Users/kieran/Git/integer.systems/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /Users/kieran/Git/integer.systems/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
at getSchema (/Users/kieran/Git/integer.systems/node_modules/relay-compiler/bin/relay-compiler:262:12)
at /Users/kieran/Git/integer.systems/node_modules/relay-compiler/bin/relay-compiler:103:19
at Generator.next ()
at step (/Users/kieran/Git/integer.systems/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /Users/kieran/Git/integer.systems/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
at
at process._tickCallback (internal/process/next_tick.js:160:7) error An unexpected error occurred: "Command failed. Exit code: 1
SCHEMA --------------------------------------------------
type User implements Node, AnonymousUser {
createdAt: DateTime!
email: String
id: ID!
isVerified: Boolean!
password: String
secret: String!
updatedAt: DateTime!
}
/* this works: type User implements Node **&** AnonymousUser { ... */
# An object with an ID
interface Node {
# The id of the object.
id: ID!
}
# It's an interface
interface AnonymousUser {
secret: String
isVerified: Boolean!
}
It is likely because your schema generating package is using its own out-dated graphql sub-dependency which prints the schema in a syntax that is incompatible with your current relay-compiler.
I'm not sure how exactly you generate your schema. I'm using get-graphql-schema and adding the following into my package.json solves the problem for me:
"resolutions": {
"get-graphql-schema/graphql": "^0.13.0"
}
If you're using another package, just replace get-graphql-schema with it. The idea is to get your schema generating package using newer version of graphql.

Maximum recursion getting shared service

I have defined two classes (Environment and ConfigurationReader). Both are registered as shared dependencies.
The Environment class tries get the current environment, but for this, needs read a configuration file via ConfigurationReader.
The sequence diagram is:
The classes are:
class Environment
{
...
public function resolve()
{
$config = DI::getDefault()->getCfg();
$config->getValue('pepe', 'db_name');
}
...
}
class ConfigurationReader
{
...
public function getValue($aConfig, $aKey)
{
$path = $this->getFile($aConfig);
}
protected function getFile($aConfig)
{
$env = DI::getDefault()->getEnv();
$path = 'config/' . $env->getShortName() . '/' . $aConfig . '.yml';
return $path;
}
...
}
And are registered and created in the index.php:
...
$di = new FactoryDefault();
$di->setShared('env', function() use ($di) {
$env = new Services\Environment($di);
$env->resolve();
return $env;
});
$di->setShared('cfg', function() use ($di) {
return new Services\ConfigurationReader($di);
});
$di->getShared('cfg');
$di->getShared('env');
...
So, PHP crash at $config = DI::getDefault()->getCfg(); and says:
PHP Fatal error: Maximum recursion depth exceeded
Any ideas ?
A couple remarks
You're passing the di to the constructor, but end up getting it statically (DI::getDefault())
regarding the infinite loop, it's because cfg needs env who needs cfg who needs env etc.....
To have the framework automatically injecting the DI into your service you should either implement InjectionAwareInterface (https://docs.phalconphp.com/en/latest/reference/di.html#automatic-injecting-of-the-di-itself) or
extend the Component class (If you need event management too, use Plugin instead of Component ). Have a look at this discussion : https://forum.phalconphp.com/discussion/383/plugin-vs-component-what-s-the-difference-
Regarding your use case, you don't give enough context for an exhaustive answer, but I think you could simplify it as:
ConfigService: Unless you use configs from different env namespaces, you should pass the value of $env->getShortName() value to the service constructor (without getting it from the env service). In our apps the env is determined by nginx based on the domain name or other parameters and passed as an environment variable to php. Also, if you don't have hundreds of config files, and your app heavily relies on them, you should read and parse them once on instantiation and store the configs in the service (as associative array, config objects, or whatever you prefer). Add some cache layer to avoid wasting resource parsing all your files on each request. Phalcons provide The Config component to do so. It comes with file adapters (only ini and associative array format but you could easily implement your own yml adapter). If most of your app config relies on configurable values, that will probably be the first component you want to instantiate (or at least declare in the di). It shouldn't dependencies to other services.
EnvService: You can access your config values by calling the config service (If you have it to extend Component, you can do something like $this->cfg->getValue($key)).

NodeBacked entity NPE - entityState is null

I've got a sample project which uses Spring Data Neo4j's advanced mapping using aspectj. It's failing in a test with NullPointerException due to the entityState attribute being null at the time when the entity is being persisted.
I can also replicate this when the server itself is spun up and I execute:
curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Test", "lastName" : "Person" }' http://localhost:8080/people
The project is at https://github.com/dhallam/spring-data-neo4j-demo and the Travis build with the logs is at https://travis-ci.org/dhallam/spring-data-neo4j-demo/builds/22538972.
I'm not sure whether I'm missing something or there is a bug that would require me to raise a JIRA issue.
Any ideas? Many thanks in advance.
Edit 1:
Versions: Java v1.7; SDNeo4j v3.1.0.M1; SDRest v2.1.0.M1; Neo4j v2.0.1; Jetty v9.0.5.v20130815; AspectJ v1.7.4
Tried adding #JsonIgnoreProperties to the Person (#NodeEntity)from Michael's comment below and it's still failing. The bit of code that is failing is when I run:
Person p = new Person();
// setters ...
p.persist();
The persist() calls
public <T extends NodeBacked> T NodeBacked.persist() {
return (T)this.entityState.persist();
}
but entityState is null.
Figured it out. The Neo4jConfig class previously extended the Neo4jConfiguration class. With the introduction of aspects, that superclass needed to be updated to be Neo4jAspectConfiguration to provide the additional neo4jRelationshipBacking and neo4jNodeBacking beans.
I've updated the github reference project at https://github.com/dhallam/spring-data-neo4j-demo and the build is passing.
Which versions do you use?
You can use #JsonIgnore for the entityState attribute.
See: http://forum.spring.io/forum/spring-projects/data/nosql/110063-unable-to-convert-nodeentity-object-to-json-with-jackson
#JsonIgnoreProperties({"entityState", "nodeId", "persistentState", "relationshipTo", "template"})

Resources