I'm learning laravel 8, and not understanding how this syntax works - eloquent

i'm making an app with a one to many relationships. A user has many posts.
in the web.php (the route file)
we wrote
Route::get('/insert', function () {
$user=User::findOrFail(1);
$post= new Post(['title'=>'title1','body'=>'bd1']);
$user -> posts()->save($post);
});
could anyone explain
the second and third line?
2- $user=User::findOrFail(1);
3- $post= new Post(['title'=>'title1','body'=>'bd1']);
why did we write User, new Post? how did this work?

With this command (line 2-) you are trying to find the user with id number 1
2- $user=User::fin`enter code here`dOrFail(1);
With this line of code (line 3-), you are inserting in the database a new record of type Post(defined in your Models directory) with the fields "title" and "body". You need to specify the user who is the author of the post:
3- $post= new Post(['title'=>'title1','body'=>'bd1']);
With the next line of code you are going to insert in the database a new record of type Post with the user you have found in your request ($user=User::findOrFail(1);)
Post::create(
['title' => 'title1', 'body' => 'bd1', 'user_id' = $user]);

Related

Adding new data with identical fields to Firebase without overwriting old data? Flutter

So, essentially I'm trying to allow my users to click a button and add each individual username to a document on Firebase. However, .set() obviously sets brand new information while .update() overwrites the old information. I've tried using SetOptions(merge: true) when writing to Firebase, but that hasn't proven effective either.
I would love it if someone could point me in the right direction and/or explain what I'm doing wrong. This is how I'm handling it currently:
CollectionReference scatterSignup =
FirebaseFirestore.instance.collection('scatterSignup');
onPressed: () async {
scatterUp.name = username;
scatterUp.code = userCode;
final scatter = scatterSignup.doc(regionUpload).set({
'name': scatterUp.name,
'code': scatterUp.code,
}, SetOptions(merge: true));
}),
I expected new information to be added without overwriting (which I believe is the function of merge unless I'm mistaken?) but that definitely didn't happen.
Essentially, I'm trying to figure out how to have a single document that consists of multiple name and code fields: one for each user trying to sign up for the list.

How can I create and update pages dynamically in Sulu CMS?

I have the following situation:
A database stores information about houses (address, number of rooms, date built, last selling price, etc.)
This database is being manipulated through an app (let's call that app the "backend house app") that cannot be directly integrated in a Sulu-driven app. I can access the stored data through an API that gives me JSON-representations of House-objects. I can also have the app launch some sort of call to a Sulu-driven app when a house is created, updated or deleted.
The Sulu-driven app (let's call that the "frontend house app") with templates for "house", "room", etc., is connected to a different database on a different server. This Sulu-driven app's website-environment shows house-pages with room-pages where some content is pre-filled through a connection to the "backend house app". Other content only exists on the database of the "frontend house app", like user comments, appraisals of interior design, etc., according to configured aspects of the Sulu-templates.
What I want to achieve, is a way to automate the creation, updating and deletion of "frontend house app"-pages based on activity in the "backend house app".
For instance, when a new house is added in the "backend house app", I want it to notify the "frontend house app" so that the "frontend house app" will automatically create the entire node-tree for the newly added house. Meaning: a "house"-page with the required data filled in, "room"-pages for each room, etc., so that the content manager of the "frontend house app" can see the entire tree of the newly added house in the workspace and can start manipulating content in the already available templates. In addition to automatically creating these pages, I also want to pre-set the rights to update and create, since the content manager of the "frontend house app" must not be able to create new rooms or change the name of the house, for instance.
I did not manage to get it working, I'll just add what I already done to show where I got stuck.
I started out with the following code, in a controller that extends Sulu's own WebsiteController:
$documentManager = $this->get('sulu_document_manager.document_manager');
$nodeManager = $this->get('sulu_document_manager.node_manager');
$parentHousesDocument = $documentManager->find('/cmf/immo/routes/nl/huizen', 'nl');
$newHouseDocument = $documentManager->create('page');
// The backendApi just gives a House object with data from the backend
// In this case we get an existing House with id 1
$house = $backendApi->getHouseWithId(1);
$newHouseDocument->setTitle($house->getName()); // For instance 'Smurfhouse'
$newHouseDocument->setLocale('nl'); // Nl is the only locale we have
$newHouseDocument->setParent($parentHouseDocument); // A default page where all the houses are listed
$newHouseDocument->setStructureType('house'); // Since we have a house.xml template
// I need to grab the structure to fill it with values from the House object
$structure = $newHouseDocument->getStructure();
$structure->bind([
'title' => $house->getName(),
'houseId' => $house->getId(),
]);
$newHouseDocument->setWorkflowStage(WorkflowStage::PUBLISHED); // You would expect this to automatically publish the document, but apparently it doesn't... I took it from a test I reverse-engineered in trying to create a page, I have no clue what it is supposed to change.
$nodeManager->createPath('/cmf/immo/routes/nl/huizen/' . $house->getId());
$documentManager->persist(
$newHouseDocument,
'nl',
[
'path' => '/cmf/immo/contents/huizen/' . Slugifier::slugify($house->getName()), // Assume for argument's sake that the Slugifier just slugifies the name...
'auto_create' => true, // Took this value from a test that creates pages, don't know whether it is necessary
'load_ghost_content' => false, // Idem
]
);
$documentManager->flush();
Now, when I fire the controller action, I first get the exception
Property "url" in structure "house" is required but no value was given.
I tried to fix this by just manually binding the property 'url' with value '/huizen/' . $house->getId() to $structure, at the point where I bind the other values. But this doesn't fix it, as apparently the url value is overwritten somewhere in the persist event chain, and I haven't yet found where.
However, I can, just for testing purposes, manually override the url in the StructureSubscriber that handles the mapping for this particular persist event. If I do this, something gets created in the Sulu-app-database - hurray!
My phpcr_nodes table lists two extra records, one for the RouteDocument referring to /cmf/immo/routes/nl/huizen/1, and one for the PageDocument referring to /cmf/immo/contents/huizen/smurfhouse. Both have the workspace_name column filled with the value default_live. However, as long as there are not also records that are complete duplicates of these two records except with the value default in the workspace_name column, the pages will not appear in the Sulu admin CMS environment. Needless to say, they will also not appear on the public website proper.
Furthermore, when I let the DocumentManager in my controller action try to ->find my newly created document, I get a document of the class UnknownDocument. Hence, I cannot have the DocumentManager go ->publish on it; an Exception ensues. If I visit the pages in the Sulu admin environment, they are hence unpublished; once I publish them there, they can be found by the DocumentManager in the controller action - even if I later unpublish them. They are no longer UnknownDocument, for some reason. However, even if they can be found, I cannot have the DocumentManager go ->unpublish nor ->publish - that just has NO effect on the actual documents.
I was hoping there would be a Sulu cookbook-recipe or another piece of documentation that extensively describes how to create fully published pages dynamically, thus without going through the 'manual labor' of the actual CMS environment, but so far I haven't found one... All help is much appreciated :)
PS: For the purposes of being complete: we're running Sulu on a Windows server environment on PHP 7.1; dbase is PostgreSQL, Sulu being a local forked version of release tag 1.4.7 because I had to make some changes to the way Sulu handles uploaded files to get it to work on a Windows environment.
EDIT: a partial solution for making a new house page if none exists already (not explicitly using the AdminKernel, but should of course be run in a context where the AdminKernel is active):
public function getOrCreateHuisPagina(Huis $huis)
{
$parent = $this->documentManager->find('/cmf/immo/routes/nl/huizen', 'nl'); // This is indeed the route document for the "collector page" of all the houses, but this doesn't seem to give any problems (see below)
try {
$document = $this->documentManager->find('/cmf/immo/routes/nl/huizen/' . $huis->id(), 'nl'); // Here I'm checking whether the page already exists
} catch(DocumentNotFoundException $e) {
$document = $this->setupPublishedPage();
$document->setTitle($huis->naam());
$document->setStructureType('huis_detail');
$document->setResourceSegment('/huizen');
$document->setParent($parent);
$document->getStructure()->bind([
'title' => $huis->naam(), // Not sure if this is required seeing as I already set the title
'huis_id' => $huis->id(),
]);
$this->documentManager->persist(
$document,
'nl',
[
'parent_path' => '/cmf/immo/contents/huizen', // Explicit path to the content document of the parnt
]
);
}
$this->documentManager->publish($document, 'nl');
return $document;
}
First of all I think the following line does not load what you want it to load:
$parentHousesDocument = $documentManager->find('/cmf/immo/routes/nl/huizen', 'nl');
It loads the route instead of the page document, so it should look like the following:
$parentHousesDocument = $documentManager->find('/cmf/immo/contents/nl/huizen', 'nl');
Regarding your error with the URL, instead of overriding the StructureSubscriber you should simple use the setResourceSegment method of the document, which does exactly what you need :-)
And the default_live workspace is wrong, is it possible that you are running these commands on the website kernel? The thing is that the WebsiteKernel has the default_live workspace as default, and therefore writes the content in this workspace. If you run the command with the AdminKernel it should land in the default workspace, and you should be able to copy it into the default_live workspace with the publish method of the DocumentManager.
I hope that helps :-)

Mongoid::Errors::DocumentNotFound in UsersController#show

I am getting the error Mongoid::Errors::DocumentNotFound in UsersController#show whenever I am trying to click on signout in my app which uses mongoid rails 4.0.1 and devise.
My user controller code is
class UsersController < ApplicationController
before_filter :authenticate_user!
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
end
The error is:
Problem: Document(s) not found for class User with id(s) sign_out. Summary: When calling User.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): sign_out ... (1 total) and the following ids were not found: sign_out. Resolution: Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.
Please help me in this issue.
A similar question, is here.
While all the first answer is important and needs to be checked (make sure you have :method => :delete on your 'Sign Out' link), it is the third answer which fixed it for my Rails 4.1.6 + Mongoid app: adding jquery_ujs.
Specifically, adding //= require jquery_ujs to my application.js file took my broken link and made it sign out sucessfully.

Zend Framework 1.11.12, Doctrine 2.2.2 integration: Error 500

I'm trying to integrate Doctrine 2 into Zend Framework (I'm new to ZF). I've look everywhere on the net but couldn't find my answer...
I've followed this recent tutorial: http://hectorpinol.com/zend-framework-1-11-and-doctrine-2-2-x-integration/ and I've managed to generate a table using the CLI.
The last step of the tuto is to add a new line in this table, simply using the Index controller. But my website doesn't work anymore (a brutal error 500, no message) because I changed the bootstrap.
if I remove the last lines I added to the _initDoctrine() method, it works again (but without Doctrine of course). Here they are:
// set the proxy dir and set some options
$config->setProxyDir(APPLICATION_PATH . '/models/Proxies');
$config->setAutoGenerateProxyClasses(true);
$config->setProxyNamespace('App\Proxies');
// now create the entity manager and use the connection
// settings we defined in our application.ini
$connectionSettings = $this->getOption('doctrine');
$conn = array(
'driver' => $connectionSettings['conn']['driv'],
'user' => $connectionSettings['conn']['user'],
'password' => $connectionSettings['conn']['pass'],
'dbname' => $connectionSettings['conn']['dbname'],
'host' => $connectionSettings['conn']['host']
);
$entityManager = \Doctrine\ORM\EntityManager::create($conn, $config);
// push the entity manager into our registry for later use
$registry = Zend_Registry::getInstance();
$registry->entitymanager = $entityManager;
return $entityManager;
Do you have any idea to unlock the situation? It's frustrating because I know I'm so close to make it work...
UPDATE1: I forgot to mention, in case it helps: I'm using WAMP on Windows. Thanks
UPDATE2: Added the parameters of the create() function.
UPDATE3: Actually it might not be an error 500. Chrome says this but Firefox just displays nothing. No answer from the server.
1) Change the environment to development to see the error message.
2) Use Bisna library instead, will save a lot of time (I don't see a point in integrating Doctrine manually well only educational purposes but you might want to save it for later).

Programmatically adding an article to Joomla

I am very new to Joomla (frankly just started exploring the possibility of using Joomla) and need help with programmatically adding articles to Joomla backend tables (please see details below). Also along the same lines, I would like to understand how should values for the columns:
parent_id
lft
rgt
level
be generated for the table jos_assets (#__assets) and what is their functional role (eg are they “pointers/indexes” analogous to, say, an os inode to uniquely indentify a file or are they more functional attributes such as identifying the category, subcategory etc)
It might help to use the following SIMPLIFIED example to illustrate what I am trying to do. Say we have a program that collects various key information such as names of the authors of web articles, the subject type of the articles, the date of articles as well as a link to the article. I want to be able to extend this program to programmatically store this information in Joomla. Currently this information is stored in a custom table and the user, through a custom php web page, can use search criteria say by author name, over a certain range of dates to find the article(s) of interest. The result of this search is then displayed along with a hyperlink to the actual article. The articles are stored locally on the web server and are not external links. The portion of the hyperlink stored in the custom table includes the relative path of the physical document (relative to the web root), so for example:
Author date type html_file
Tom 08-14-2011 WEB /tech/11200/ar_324.html
Jim 05-20-2010 IND /tech/42350/ar_985.html
etc.
With all the advantages that Joomla offers over writing custom php search and presentation pages as well as trending etc, we would really like to switch to it. It seems that among other tables for example that #__assets and #__content can be populated programmatically to populate Joomla from our existing php program (which is used to compile the data) and then use Joomla.
Any examples, suggestions and help is greatly appreciated
Kindest regards
Gar
Just an initial note: Joomla 1.6/1.7 are pretty similar. 1.5 not so much. I'll assume 1.6/1.7, as that's what I'd recommend as a base for a new project.
First up, you'll need to be running with access to the Joomla framework. You could do this through a Component, or a module, or a cron that bootstraps it or whatever. I won't go though how to do that.
But once you do that, creating an article is reasonably simple.
<?php
require_once JPATH_ADMINISTRATOR . '/components/com_content/models/article.php';
$new_article = new ContentModelArticle();
$data = array(
'catid' => CATEGORY_ID,
'title' => 'SOME TITLE',
'introtext' => 'SOME TEXT',
'fulltext' => 'SOME TEXT',
'state' => 1,
);
$new_article->save($data);
The actual list of fields will be a bit longer than that (required fields etc), but you should get sane error messages etc from the Joomla framework which illuminate that.
So in summary:
Load up the Joomla framework so you have access to the DB, components, models, etc
Include the com_content article class, which will handle validation, saving to the database etc for you
Create an article instance with the required fields filled in as appropriate
Call save()
Now that I think about it, that'll probably work in 1.5...
Found a better way to do this without any errors Create a Joomla! Article Programatically
$table = JTable::getInstance('Content', 'JTable', array());
$data = array(
'catid' => 1,
'title' => 'SOME TITLE',
'introtext' => 'SOME TEXT',
'fulltext' => 'SOME TEXT',
'state' => 1,
);
// Bind data
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}