How to pass object in views in laravel - laravel

I'm having a set of html codes which are being called in a foreach statement in views, I'm trying to push array of object to get the views through controller.
Following is my controller code:
public function get_template($id)
{
$template = Template::findOrFail($id);
$getplugin = json_decode($template->templatedata);
$plugins = Plugin::all();
$userid = $template->user->id;
return view('nitseditor.test', ['plugins' => $plugins, 'template'=> $template, 'getplugin' => $getplugin, 'userid' => $userid]);
}
In my views I'm calling like this:
#foreach($getplugin as $renderer)
#include('themes.' . $template->theme->name . '.Plugins.' . $plugins->find($renderer)->type . '.' . $plugins->find($renderer)->id, ['content' => $plugins->find($renderer)->userplugins()->whereUserId($userid)->first()->pivot->contents])
#endforeach
Views or HTML code which are being generated:
<div id="slideshow">
<div class="revolution-slider">
<ul>
<!-- SLIDE -->
#foreach($content->slider as $sliders)
<li data-transition="{{ $sliders->transition }}" data-slotamount="{{ $sliders->slotamount }}" data-masterspeed="{{ $sliders->masterspeed }}">
<!-- MAIN IMAGE -->
<img src="{{ URL::asset($sliders->url) }}" alt="">
</li>
#endforeach
</ul>
</div>
</div>
Now I'm getting an error of
Trying to get property of non-object (View: C:\wamp\www\NitsEditor\resources\views\themes\Miracle\Plugins\Slider\2.blade.php) (View: C:\wamp\www\NitsEditor\resources\views\themes\Miracle\Plugins\Slider\2.blade.php)
While executing diedump the below code in foreach loop:
foreach ($getplugin as $item){
$plugincontents[] = Plugin::findOrFail($item)->userplugins()->whereUserId($userid)->first()->pivot->contents;
}
dd($plugincontents);
I'm able to get the JSON output which holds the information of that particular view. Like this below:
array:2 [▼
0 => "{"slider": [{"url": "img/home/bg.jpg", "slotamount": "7", "transition": "zoomin", "masterspeed": "1500"}, {"url": "img/home/bg2.jpg", "slotamount": "7", "transition": "zoomout", "masterspeed": "1500"}, {"url": "img/home/LOMEg.png", "slotamount": "7", "transition": "slidedown", "masterspeed": "1500"}]}"
1 => "{"logo": {"logolink": "index.html", "logoimage": "img/home/nitseditorlogo.png"}, "pages": [{"pagelink": "index.html", "pagename": "Mysite"}, {"pagelink": "templates.html", "pagename": "Templates"}, {"pagelink": "aboutus.html", "pagename": "About Us"}, {"pagelink": "contactus.html", "pagename": "Contact Us"}]}"
]
Please help me out. Thanks.

instead of $getplugin = json_decode($template->templatedata); use $getplugin = json_decode($template->templatedata,true);

Well, while doing cross checks I came to know that I need to json_decode in my data in views. I tried and got the result,
In my Views I did json_decode to the array like this:
#foreach($getplugin as $renderer)
#include('themes.' . $template->theme->name . '.Plugins.' . $plugins->find($renderer)->type . '.' . $plugins->find($renderer)->id, ['contents' => json_decode($plugins->find($renderer)->userplugins()->whereUserId($userid)->first()->pivot->contents)])
#endforeach
And finally getting the results as desired.

Related

Laravel 5.0: Route with query string

I am using laravel 5.0, I am sending a query string on A tag with an id.
I am getting id but not the query string data
Below is the code:
View
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<div class="img-decor">
<a href="{{url('buycarddetail/'.$retailer->id)}}" class="">
<img src="{{ assetnew('uploads/client_image/'.$retailer->image) }}" alt="..." class="img-rounded" width="200">
</a>
<div class="deals-title">
{{ $retailer->name }}
<div class="sub-details">Save up to {{ $retailer->discount }}%</div>
</div>
</div>
</div>
Controller
public function buycarddetail($id = null, Request $request)
{
echo $id;
echo '<pre>'; $data = $request->all(); exit;
return view('buycarddetail');
}
Route
Route::get('buycarddetail/{id}', ['as' => 'buycarddetail', 'uses' => 'HomeController#buycarddetail']);
I want to use the query string data for further process on controller
Please help
Based on your code you're not actually appending any query string when generating the link {{url('buycarddetail/'.$retailer->id)}}.
As per your comments you can do this to generate a link to your route with the query string.
{{ route('buycarddetail', ['id' => $retailer->id, '_token' => csrf_token(), 'brand' => 'test', 'buybrand' => 'example']) }}
This example would generate a link like
http://example.com/buycarddetail/17?_token=QHE8va7stXUOPabwTjKmXyJxdsuPSZ9VbH3uThwx&brand=test&buybrand=example

Filter items by category in Laravel October

I have a document model with a $belongsTo categories relationship, everything is working well and I'm able to assign categories to documents and list them all on the frontend, but what I'm struggling with is filtering the results by category.
I have 3 categories and 3 col-md-4 columns, in each column, the documents should be listed and filtered via their category, how do I do this with twig using components?
My documents.default component file looks like this:
{% set documents = __SELF__.documents %}
<ul class="record-list list-unstyled ">
{% for document in documents %}
<li class="ul-text-black">
{{document.name }}
</li>
{% endfor %}
</ul>
My documents component code:
<?php namespace Myplugin\Documents\Components;
use Cms\Classes\ComponentBase;
use Myplugin\Documents\Models\Document;
class Documents extends ComponentBase
{
public function componentDetails(){
return [
'name' => 'Documents List',
'description' => 'Custom Component to list documents by category'
];
}
public function defineProperties(){
return [
'results' => [
'title' => 'Number of Documents',
'description' => 'How many documents do you want to display?',
'default' => 24,
'validationPattern' => '^[0-9]+$',
'validationMessage' => 'Only numbers allowed'
],
'sortOrder' => [
'title' => 'Sort Documents',
'description' => 'Sort documents',
'type' => 'dropdown',
'default' => 'name asc',
]];
}
public function getSortOrderOptions(){
return [
'name asc' => 'Name (ascending)',
'name desc' => 'Name (descending)',
];
}
public function onRun()
{
$this->documents = $this->loadDocuments();
}
protected function loadDocuments(){
$query = Document::all();
if ($this->property('sortOrder') == 'name asc') {
$query = $query->sortBy('name');
}
if ($this->property('sortOrder') == 'name desc') {
$query = $query->sortByDesc('name');
}
if ($this->property('results') > 0) {
$query = $query->take($this->property('results'));
}
return $query;
}
public $documents;
}
My page looks like this
<div class="row">
<div class="col-md-4">
<p class="text-black">
<strong>FINANCIAL</strong>
</p>
{% component 'documents' %} // Only documents from financial category
</div>
<div class="col-md-4">
<p class="text-black">
<strong>ANALYTICS</strong>
</p>
{% component 'documents' %} // Only documents from analytics category
</div>
<div class="col-md-4">
<p class="text-black">
<strong>INVESTMENT</strong>
</p>
{% component 'documents' %} // Only documents from investment category
</div>
How do I display the documents list but filter them by category? Something like this?
{% partial "documents-financials" category="Financials" %}
You should be able to access the properties in your Documents component using $category = $this->property('category');
There's documentation on accessing component properties on the OctoberCMS website: https://octobercms.com/docs/plugin/components#component-properties
I can then see that you're loading all documents and filtering them using the Laravel Collection. I would suggest changing this and doing it on the database first. It'll be far more efficient.
$category = $this->property('category');
$results = $this->property('results');
$documents = Document::whereHas('category', function ($query) use ($category) {
return $query->where('name', $category);
})
->orderBy('name', 'ASC')
->take($results)
->get();
If you want to group your documents and then output them, you could do the following:
$this->documents = Document::with('category')
->orderBy('name', 'ASC')
->take($results)
->get()
->groupBy('category.name');
See https://laravel.com/docs/5.3/collections#method-groupby
Then in your component template:
<div class="row">
{% for group in documents %}
<div class="col-md-4">
<p class="text-black">
<strong>FINANCIAL</strong>
</p>
<ul class="record-list list-unstyled">
{% for document in group %}
<li class="ul-text-black">{{document.name }}</li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>

How to pass array to flash message?

I want to send array of additional_feature that they are exist to flash message. Now i only send one additional_feature. Any suggestion how can i do that?
if(!empty($additional_features)){
foreach($additional_features as $additional_feature){
$data = [
'name' => $additional_feature,
];
if (!Feature::where('name', '=', $additional_feature)->exists()) {
$additional = Feature::firstOrCreate($data);
$additional_ids[] = $additional->id;
}
else{
return redirect()->back()->withFlashMessage($additional_feature . ' exists!');
}
}
}
You can use session() instead of with():
session->flash('someVar', $someArray);
Another thing you could try is to seriallize array and pass it as string. Then unserilize it and use.
Also, you could save an array using simple session:
session(['someVar' => $someArray]);
Then get it and delete manually:
session('somevar');
session()->forget('someVar');
We had the same problem and forked the package. you can find it here:
Forked at first from Laracasts/Flash to use multiple message
#if (Session::has('flash_notification.message'))
#if (Session::has('flash_notification.overlay'))
#include('flash::modal', ['modalClass' => 'flash-modal', 'title' => Session::get('flash_notification.title'), 'body' => Session::get('flash_notification.message')])
#else
<div class="alert alert-{{ Session::get('flash_notification.level') }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! Session::get('flash_notification.message') !!}
</div>
#endif
#endif
And the content of the include flash::modal
#if (Session::has('flash_notification.messages'))
#foreach (Session::get('flash_notification.messages') as $flashMessage)
#foreach($flashMessage as $type => $message)
<script>
$(function() {
var message = ('{{ $message }}<br>').replace(/'/g, "’");
customFlashMessage({
type: "{{ $type }}",
message: message
});
});
</script>
#endforeach
#endforeach
#endif
return redirect()->back()->with(['session1' => $value, 'session2' => $value]);
In the blade template:
{{ Session::get('session1') }}
{{ Session::get('session2') }}

Laravel Image intervention showing me Call to a member function getClientOriginalName() on a non-object Laravel

I am using Laravel Image Intervention Package with drop-zone plugin. And for sure I have installed it properly. When I try to upload images and then submit the form its showing me the following error message
"Call to a member function getClientOriginalName() on a non-object"
Even this error message showing me if i blank this input field form. In that case it is expected to me not showing me any error message as it is not mandatory field to submit the form But it did.
I have two query.
1) what's going wrong in my code
2) Right now I am trying to upload single image. For multiple images I want to store the files info as an array. In that case what would my code in controller.
Here is my live link you can check from here
http://thetoppinghouse.com/laravel/public/admin/index/create
http://laravel.io/bin/Jxmzo
Here is my controller code
public function store()
{
$validator = Validator::make($data = Input::all(), Index::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
if ($validator->passes()) {
$index = new Index;
$index->name = Input::get('name');
$index->category_ID = Input::get('category_ID');
$files = Input::file('files');
$filename = date('Y-m-d-H:i:s')."-".$files->getClientOriginalName();
$path = public_path('img/index/' . $filename);
Image::make($files->getRealPath())->save($path);
$index->files = 'img/index/'.$filename;
$index->save();
return Redirect::route('admin.index.index')->with('message', 'Index Created');
}
}
// Form Code
<ul class="post-list">
<li>
{{ Form::label('parent_ID', 'Category') }}
{{ Form::select('parent_ID',Category::lists('category_name','id'),Input::old('category'),array('class' => 'form-control input-sm', 'id' => 'parent_ID')) }}
</li>
<li>
{{ Form::label('name', 'Index Name') }}
{{ Form::text('name', null, array( 'class' => 'form-control input-sm', 'placeholder' => 'Name' )) }}
{{ $errors->first('name', '<p class="error">:message</p>' ) }}
</li>
<li>
{{ Form::label('image', 'Cover Image') }}
</li>
<div class="dropzone" id="DropzoneArea">
<div class="fallback">
<input name="files" type="file" id="files" multiple>
</div>
</div>
{{ Form::submit('Save') }}
</li>
</ul
handle the file upload with dropzone like,
var fileDropzone = new Dropzone("div#DropzoneArea", {
url: '/upload', // customize the URL
addRemoveLinks: false
});
then when u uploading something upload action will call and u can handle the file upload in that action. then you can return the server file path of uploaded file.
fileDropzone.on("success", function (file,data,e) {
var hiddenInput = $('<input name="filePath" type="hidden value=" '+ data.path +' "">');
// and append the hiddenInput in to the form
});
then after success upload you can set the server path of the uploaded file in a input hidden field. after you submit the form you can get the file by hidden field value.
when you submit the form, get uploaded file as,
$filePath = Input::input('filePath');
$file = File::get($filePath);

Getting database value in smarty template

I have php file called testfun.php
<?php
$conn=mysql_connect("localhost","root","") or die("unabke to connect");
$db=mysql_select_db("smartyform",$conn) or die("databse error");
require 'Smarty/libs/Smarty.class.php';
$smarty = new Smarty;
$sel=mysql_query("select * from form");
while($row=mysql_fetch_array($sel))
{
$id=$row[0];
$name=$row[1];
}
$smarty->assign('id',$id);
$smarty->assign('name',$name);
$smarty->display('testfunction.tpl');
?>
I have tpl file called testfunction.tpl
<body>
<ul>
{$id}
:
{$name}
</ul>
</body>
</html>
When I run the testfun.php I got this output:
16 : dg
But I want output like:
1:d
d:g
What should I do ?
You have to pass your data as an array to smarty. So in PHP you should do something like this:
while($row=mysql_fetch_array($sel))
{
$data[] = array(
"id" => $row[0],
"name" => $row[1]
);
}
$smarty->assign("data", $data);
Then, in your Smarty template you have to use foreach to list your items:
{foreach $data as $item}
{$item.id}:{$item.name}
{/foreach}

Resources