Laravel check if Request has collection - laravel

I want to run an if statement over each of my posted requests and if any are a collection do something different.
When I die dump $request->all I have an array that looks like this;
"_token" => "MMRFBAgyThsIHzITzT26Qwdp4L6HDV0JTPGs6h"
"page_name" => "Travel"
"heading" => "Travel Europe"
"textarea" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostru ▶"
"seo_title" => "travel"
"seo_description" => "travel"
"attribute_1" => "Food"
"attribute_2" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor."
"attribute_3" => "Hotels"
"attribute_6" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor."
"attribute_5" => "Events"
"attribute_4" => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor."
"attribute_7" => null
"attribute_8" => null
"attribute_9" => UploadedFile {#233 ▶}
The data will be different so I can't write anything static e.g.$request->input('attribute_9')
This is how I'm currently handling the attributes which are the unknown requests.
$input = $request->all();
foreach($input as $key=>$value) {
if(strstr($key,'attribute_')) {
$i = str_replace("attribute_", "", $key);
if (!empty($value)) {
if ($value instanceof Illuminate\Http\UploadedFile) {
dd('lets have a collection...');
}
Attribute::where('id', $i)->update(['value' => $value]);
} else{
Attribute::where('id', $i)->update(['value' => '']);
}
}
}
You can see I've tried to check the $value using instanceOf but that hasn't worked. The if statement is never true and the page just returns.
Example of attribute input submission -
#if($comp_attr['data_type'] == 'file')
<div class="form-grp img-form" style="width: {{ $comp_attr['width'] }}%;">
<label>Banner Image</label>
<span class="img-hold">
{{ $banner }}
</span>
<input type="{{ $comp_attr['field_type'] }}" name="attribute_{{ $comp_attr['id'] }}" />
</div>
#else
<div class="form-grp" style="width: {{ $comp_attr['width'] }}%;">
<label>{{ $comp_attr['label'] }}</label>
<input type="{{ $comp_attr['field_type'] }}" name="attribute_{{ $comp_attr['id'] }}" value="{{ $comp_attr['value'] }}" />
</div>
#endif

I believe you are trying to get the $_FILES
So you can get all the files using
$request->allFiles();
This will return you all the files in the request. then you can perform any action on it.
Hope this helps

Instead of
name="attribute_{{ $comp_attr['id'] }}"
Try
name="attributes[{{ $comp_attr['id'] }}]"
Notice the new 's' ^ , and the brackets on either side of the {{ }}
By using brackets we convert it to an associative array, keyed by the blade variable.
Then on the php side you can do something like this:
foreach($request->get('attributes') as $i => $value)
{
...
}

Related

Magento 2 - Multiline content for static block installer

What is best practice on Magento 2 for having multiline html in content?
On Magento 1 if I remember right you would use some thing <<<'EOT'
$cmsBlockData = [
'title' => "About Us",
'identifier' => "aboutus",
'content' => "
<div class="intro-block" style="background-image: url({{view url='images/content/about-us-img1.jpg'}})">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.</p>
</div>
",
]
actually there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD') and heredoc(<<<EOD) strings. reference
You can use here document operator (<<<) then use a word like HTML, EOD, EOT or any string you want!
Some handy notes when you wanna use heredoc : here
Sample :
$html = <<<HTML
<div class="intro-block" style="background-image: url({{view url='images/content/about-us-img1.jpg'}})">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit.</p>
</div>
HTML;
$cmsBlockData = [
'title' => "About Us",
'identifier' => "aboutus",
'content' => $html
",
]

Trying to get property 'id' of non-object in laravel session foreach

Im practicing laravel and right now Im in the session topic
this is my controller
public function set(Request $request){
$product = Product::findOrFail($request->input('id'));
session()->put('product', $product);
return redirect()->route('cart');
}
when i tried to echo the{{session()->get('product')}} on my blade it produce an output of
{
"id":9,
"name":"Lorem ipsum dolor sit amet",
"description":"Proin pretium, mauris id convallis tempus, lorem enim tincidunt nulla, vel pharetra sapien odio eget ligula. Sed maximus, massa sit amet condimentum bibendum, nisi ante vestibulum ipsum, ut ornare justo lorem mollis justo.",
"price":"22.21",
"cover_image":"JRwg9TSKTvUTvuij.jpg",
"created_at":"2018-07-20 03:47:57",
"updated_at":"2018-07-20 03:47:57"
}
but when i tried to use foreach on it by using
#foreach(session()->get('product') as $key)
{{$key->id}}
#endforeach
it shows an error of Trying to get property 'id' of non-object
can someone guide me why I'm I getting this error thanks.
You are iterating through your single object but what you seem to need to do is:
{{ session()->get('product')->id }}
If you want to loop then you can do:
#foreach (session()->get('product')->toArray() as $key => $value)
{{ $key }}: {{ $value }}
#endforeach
This will result in:
id: 9
name: Lorem ipsum dolor sit amet
description: Proin pretium, mauris id convallis tempus, lorem enim tincidunt nulla, vel pharetra sapien odio eget ligula. Sed maximus, massa sit amet condimentum bibendum, nisi ante vestibulum ipsum, ut ornare justo lorem mollis justo.
price: 22.21
cover_image: JRwg9TSKTvUTvuij.jpg
created_at: 2018-07-20 03:47:57
updated_at: 2018-07-20 03:47:57
However, just as a sidenote this is bad practice because your coupling your view with a session entry. Ideally your view would just take a product object as a view parameters and use that directly. That way you can pass it that object either from the session or from a database query.
If you are trying to get single value from an object you can get like this.
{{ session()->get('product')->id }}
Or If you wish to print all data, First you have to convert object into an array then use foreach.
#foreach (session()->get('product')->toArray() as $key => $value)
{{ $key }}: {{ $value }} </br>
#endforeach
Try it this way :
#foreach(session()->get('product') as $key)
{{$key['id']}}
#endforeach
You are trying to iterate an object. When you try to do this you get the public properties from the object. In your example $key is one of those properties, not the model itself.
When you echo {{ }} a Model __toString gets called which returns the serialized model as json.
If you want that model's id you can just grab it like normal. session('product')->id
If you want you can serialize the Model to an array:
foreach ($model->toArray() as $key => $value) {
...
}

Error: JSON.parse: expected ',' or ']' after array element

Am newbie to Json am getting this error while call json my json file expected ',' or ']'
[
{
"modules":
[
{
"title":"name of module1",
"description":"description of module1",
"weeks":[{"id":1, "title":"Week 01"}]
},
{
"title":"name of module2",
"description":"description of module2",
"weeks":[{"id":2, "title":"Week 02"},{"id":3,"title":"Week 03"}]
}
]
},
{
"products":
[
{
"url":"http://dummyimage.com/242x200/f3f3f3/2d2d2d.png",
"description":"Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.",
"viewurl" : "/",
"savebtn" : "save"
},
{
"url":"http://dummyimage.com/242x200/f3f3f3/2d2d2d.png",
"description":"Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.",
"viewurl" : "/",
"savebtn" : "save"
}
]
}
]
hope i did correct i dont know what is happening its getting Error: JSON.parse: expected ',' or ']' after array element am attempting to use in angular js controller
app.controller('settingsController', function($scope, $http){
$http.get('assets/javascripts/datas.json').then(function(result){
$scope.employe = result.data;
$scope.prod = result
})
});
and in view
<div class="col-sm-6 col-md-4" ng-repeat="datas in prod.products">
<div class="thumbnail">
<img ng-src="{{ datas.url }}" alt="product">
<div class="caption">
<h3>{{ datas.caption}} </h3>
<p>{{ datas.description}}</p>
<p><a role="button" class="btn btn-primary" ng-href="{{datas.viewurl}}">Button</a> <a role="button" class="btn btn-default" href="#">{{datas.savebtn}}</a></p>
</div>
</div>
</div>
and the error in console
Error: JSON.parse: expected ',' or ']' after array element at line 76 column 9 of the JSON data cc#/test/assets/javascripts/vendors/angular.js:14:289 Ud/this.defaults.transformResponse<#/test/assets/javascripts/vendors/angular.js:69:58 xc/<#/test/assets/javascripts/vendors/angular.js:68:352 r#/test/assets/javascripts/vendors/angular.js:7:288 xc#/test/assets/javascripts/vendors/angular.js:68:336 b#/test/assets/javascripts/vendors/angular.js:70:65 ye/e/l.promise.then/K#/test/assets/javascripts/vendors/angular.js:100:59 ye/f/<.then/<#/test/assets/javascripts/vendors/angular.js:101:235 Zd/this.$get
This error occurred for me when I parsed JSON from a string literal. When I copied in the JSON, I forgot that the escape sequences would need to be double escaped.
Example of the problem:
var data = JSON.parse('[{"key": "This value has \"a quoted\" string"}]');
While the string value is valid JSON, the escape sequences are lost. Then need to be double escaped:
Corrected version:
var data = JSON.parse('[{"key": "This value has \\\"a quoted\\\" string"}]');
Well for me the problem occurs if I have a :// (e.g. http://) inside my json stirng for this reason I replaced it and it worked.

How can I integrate fitVids.js into a .load function?

I'm new to jquery and I need to integrate a bit of code and I'm calling it from an external html file with the .load() function. That part of code it's a .div containing a video and a description. All I need to do is to make fitVids work on the code loaded from the external file.
This is the html loaded in the div.featured-container:
<div class="featured-container">
<div class="container player clearfix">
<div class="span8 video-container">
<iframe width="600" height="338" src="http://www.youtube.com/embed/QkhqI49QeaM?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
<div class="span4 featured-content">
<div class="feat-meta">May 8, 2010 at 16:50 / by Silviu Stefu</div>
<h2>Retiner - Mobile UI Kit</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.
</p>
<a class="button-normal" href="">Read More...</a>
</div>
</div>
</div>
And here is the JS:
//load the first list item link
var firstLoad = $('.thumbnails li:nth-child(2) a').attr('href')+' .player';
$('.featured-container').load(firstLoad,'',showTheContent());
function showTheContent() {
$('.player').fitVids().fadeIn('slow');
}
//load the links on click
$('.thumbnails li a').click(function(){
var toLoad = $(this).attr('href')+' .player';
$('.player').fadeOut('slow',loadContent);
$('#load').remove();
$('#load').fadeIn('normal');
function loadContent() {
$('.featured-container').load(toLoad,'',showNewContent());
}
function showNewContent() {
$('.player').fadeIn('slow',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
So, where I should put the .fitVids() function to make the fideo fluid?
I would use the success function for this, so that if its loaded run the code.
$("#success").load("file.html", function(response, status, xhr) {
if (status == "succes") {
// your code
}
});

wordpress get_posts() returns empty the_ID()

I've got a problem with loading a list of posts in a certain category via AJAX. the funny part is, that I get a right amount of posts, I get the excerpts right for each post, but ID, and title are empty, plus the date is wrong (1.1.1970). this is my function within functions.php:
function ajax_cat(){
if( isset($_GET['action'])&& $_GET['action'] == 'ajax_cat'){
$my_id = htmlspecialchars($_GET["id"]);
$args = array(
'offset' => 0,
'category' => $my_id,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish' );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<div class="nadpis1" id="<?php the_ID(); ?>" >
<?php the_title(); ?>
<span class="sipka"><?php the_date("d.m. Y"); ?></span>
</div>
<div class="vnutro" ><?php echo the_excerpt();?></div>
<?php endforeach;
die();
}
}
originally this code was inside the loop and worked well. this is what i get now:
<div class="nadpis1" id="" >
<span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></div>
<div class="nadpis1" id="" >
<span class="sipka"></span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing ultrices posuere. Aenean et egestas enim. Phasellus sit amet nisl elit. Sed pulvinar, purus nec commodo condimentum, lectus risus lacinia urna, sed ultrices magna est vitae turpis. Sed convallis pulvinar gravida. Sed non sem sem, at lobortis tellus. Etiam commodo risus vitae diam cursus volutpat. [...]</p></div>
<div class="nadpis1" id="" >
<span class="sipka"></span>
</div>
<div class="vnutro" ><p>gfdgdfsgngfjty ty jghj ty jtyhjghj dh gfdj5 fgjfdthbkdfgxhjsrgv ,f xfhbtyj dc rtjdtxhvcntydxvhctr shxfc</p></div>
<div class="nadpis1" id="" >
<span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Vitajte vo WordPress. Toto je váš prvý článok. Môžete ho upraviť alebo vymazať a potom už len začať písať!</p></div
>
thanks for any suggestions!
You can't use the_ functions outside of The Loop. Try using get_the_title($postid); and similar get_ functions. Note that the get_ functions don't display the value, they return it, so you'll have to use echo get_the_title($postid);.
Edit: Nevermind, I see that you're using setup_postdata(). However, it could still be worthwhile to use the functions which pass in the ID instead of the ones that change global settings. Try inspecting $post with print_r to see which data you already have in your foreach loop without calling a whole bunch of other database queries.

Resources