Storing a new post tag if it doesn't exist in the table? - laravel

I have a single input field (using select2 plugin) in a blog post form which allow user to insert post tags from existing tags in the table or create new ones and store them in the Tag table and also attach them to the post when they hit submit post button. I've managed to get this work by filtering the input with array_filter(), if the input is !is_numeric the input will first get stored in Tag table and then attach the id to the post.
The problem with this is that it's not working when the new tag from the input is in full numeric type, like 2017 tag. Is there a solution to get this working so the new tag is not limited to string only but also numeric type ? and if possible, I don't want to use any package for this.
The post store method :
public function store(PostsReq $request) {
$input = $request->all();
$post = Post::create($input);
//Handle the tags
$getTags = $request->input('tagspivot');
$oldTags = array_filter($getTags, 'is_numeric');
$newTags = array_filter($getTags, function($item) {
return !is_numeric($item);
});
foreach ($newTags as $newTag) {
if ($tag = Tag::create(['title' => strtolower(trim($newTag))])) {
$oldTags[] = $tag->id;
}
}
$post->tags()->attach($oldTags);
// Upload Image
if ($request->hasFile('image')) {
$input['image'] = $this->uploadImage($request, $post);
}
return redirect()->route('postindex')->with($this->postStoreSuccess);
}

Here is three lines of code would be more than enough:
$tag = Tag::firstOrCreate([
'title' => $request->input('tagspivot'),
]);
You don't need to check for !is_numeric. However, in your form don't use tag id as value. use the title.

Related

how to return to a specific page after form submit based on value laravel

i have a logic whereby on form submission i want to return to specific page based on a certain value the user choosed when submiting the form.the form works well but when i try to return it doesnt work.where might i be missing the point here.
public function addtoorder(Request $request){
$userid=Auth::user()->id;
$addresses=Deliveryaddress::where('user_id',$userid)->first();
if($request->isMethod('post')){
$data=$request->all();
$order = new Order();
$order->name = Auth::user()->name;
$order->phone =$addresses->phone;
$order->county =$addresses->shipcharges->county;
$order->town =$addresses->towns->town;
$order->order_status="New Order";
$order->payment_method = $request->payment_method;
$order->user_id =$userid;
$order->grand_total = Session::get('grand_total');
$order->shipping_charges=$addresses->shipping_cost;
$order->save();
}
if($data=="SKRILL"){
return view('frontend.product.skrill');
}elseif($data=="PAYPAL"){
return view('frontend.product.paypal');
}
}
}
i have been able to save the data on the database but am unable to return to the specific pages.rather it return to blank page without any error,but it saves the data to the orders table perfectly.
I guess blank screen means that nothing was returned, because you are trying to check whether $data(which is array) is equal to some string.
My thoughts would be for you to try check string in your if statement.
Like this
if($data['payment_method'] === "SKRILL"){
return view('frontend.product.skrill');
}elseif(data['payment_method'] === "PAYPAL"){
return view('frontend.product.paypal');
}

Magento 2.3 graphql get custom attribute option values

I’m pretty frustrated with the graphql api of Magento. How is it not possible to receive the values of a custom attribute. I mean it’s easy to make a custom select-option attribute and making it available through graphql but you are only getting the integer value.
What’s the best procedure to following
1. Query the complete attribute to get the value
2. Extending the graphql schema (this involves a developer every time the client changes something)
3. Am I missing some functionality inside the graphql endpoints to Fix this?
From Native GraqpQl we cannot get the expected result.But we can write a custom module with the graphql and achieve it.What my suggestion is get the product detail by sku using _productRepository->get($sku);. This will return the entire product details.So you can get the attribute data by using $attributes = $_product->getAttributes(); Here is my data provider file.
/**
* #params string $sku
* this function return all the product data by product sku
**/
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
/**
* #params int $id
* this function return all the word of the day by id
**/
public function getAttributesBySku( $sku ){
$_product = $this->getProductBySku($sku);
$attributes = $_product->getAttributes();// All Product Attributes
$attributes_data = [];
$x=0;
foreach ($attributes as $attribute) {
if($attribute->getIsUserDefined()){ // Removed the system product attribute by checking the current attribute is user created
$attributeLabel = $attribute->getFrontend()->getLabel();
$attributeValue = $attribute->getFrontend()->getValue($_product);
if($attribute->getAttributeCode()=="language"){
$attributeLabelAndValue = $attributeLabel." - ".$attributeValue;
$attributes_data[$x]['atr_data'] = $attributeLabelAndValue;
}
}
$x++;
}
return $attributes_data;
}
This code will return the need
$attribute->getFrontend()->getLabel(); this will return the label and
$attribute->getFrontend()->getValue($_product); this will return the value.
To check the entire graphQl query and resolver file kindly view How to get product attribute value, label using GraphQl in Magento 2.3?
Hope this will help you.
You can try creating custom graphql attribute with custom resolver.
$product = $this->_productRepository->getById($value['entity_id']);
$data = array();
foreach ($args['fields'] as $fi) {
$att = $product->getResource()->getAttribute($fi);
if (isset($att) && $att) {
if (in_array(
$att->getFrontendInput(),
['multiselect', 'select']
)) {
$data[$fi . '_label'] = $product->getAttributeText($fi);
}
$data[$fi] = $product->getData($fi);
}
}
return json_encode((object) $data);
which should display all provided attributes with their labels.
"sku": "testProduct",
"fabric": 60,
"work": 65,
"dynamicAttributes": "{
"fabric_label":"Pure Silk",
"fabric":"60",
"work_label":"Tanchoi",
"work":"65"
}",
Check out entire module here

Contentful/Laravel Delivery API setInclude does not work as expected

While using the contentful laravel sdk the set include is not fetching any of the assets that belong to the entries I fetch. The code below (mine):
public function index()
{
$query = $this->query
->setContentType('gallery')
->setInclude(10);
$entry = $this->client->getEntries($query);
if (!$entry) {
abort(404);
}
$data = ['galleries' => $entry];
return view('welcome', ['data' => $data]);
}
The contenful example:
// contentful.php 3.0
$client = new Contentful\Delivery\Client(
'<content_delivery_api_key>',
'<space_id>',
'<environment_id>' // Defaults to "master" if ommitted
);
$query = (new Contentful\Delivery\Query())
->setInclude(2);
$entries = $client->getEntries($query);
my results:
[]
I expect for the previewImage and Images array to include the 'fields' that contain the location of the file. I only get 'sys'. I can't see why the include is not fetching this data. If i set setInclude to 20, over the limit i get an error. Below
What should i do differently? I achieved the desired results in a javascript frontend project, but with laravel i get nothing.
The include is actually working fine. Internally, linked entries/assets are represented using a Link object, which is resolved to an actual entry/asset as soon as you access the field (in your case, that's done with $entry->getPreviewImage(), which will return the Asset object that was loaded in your previous query).
This means that if you dump the entry you won't see the actual object you're expecting in the previewImage field, but everything will work fine if in regular use.

In a user's Edit Info form, how do I include the name of the field(s) and user's input value(s) in a response from the model

On a Yii2 project, in a user's Edit Info form (inside a modal):
I'm currently figuring out which fields were changed using the jQuery .change() method, and I'm grabbing their value with jQuery's .val() method.
However, I want to do less with JavaScript and do more with Yii's framework.
I can see in the Yii debugger (after clicking into the AJAX POST request) that Yii is smart enough to know which fields were changed -- it's showing SQL queries that only UPDATE the fields that were changed.
What do I need to change in the controller of this action to have Yii include the name of the field changed -- including it's value -- in the AJAX response? (since my goal is to update the main view with the new values)
public function actionUpdateStudentInfo($id)
{
$model = \app\models\StudentSupportStudentInfo::findOne($id);
if ($model === null) {
throw new NotFoundHttpException('The requested page does not exist.');
}
$model->scenario = true ? "update-email" : "update-studentid";
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->renderAjax('_student_support_alert_success');
}
return $this->renderAjax("_edit_student_info",[
"model" => $model,
]);
}
I'm currently returning a static success view.
You can use $model->dirtyAttributes just after load the data to get a $attrib => $value pair array.
http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#getDirtyAttributes()-detail (this docs says:)
Returns the attribute values that have been modified since they are loaded or saved most recently.
The comparison of new and old values is made for identical values using ===.
public array getDirtyAttributes ( $names = null )
(sorry for formatting, sent by mobile)

Loading page dynamically from database via id in controller

I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)

Resources