Need to go through 2 objects at the same time with VUEJS - laravel

I just want to throught POSTS and USERINFO at the same pace, in a way that in show the right user avatar for a given post
Objects
posts : {!! $posts !!},
userinfo : {!! $userinfo !!},
Template
< v-cloak v-for="post in posts">
<div v-bind:style="{ backgroundImage: 'url(' + post.picture + ')' }">
</div>
Dont know how... basicly...

The correct way (IMHO) is to provide the data to the template in a correct way, so the template just loops through the data the least amount of time.
To support that a computed value may be the easiest way to implement.
You can create a complex loop using js in you computed value, and then you reduce any complex logic in the template. This may also reduce the number of renders or re-computations needed if other parts of the component or template are changing.
other options are to update data.variable using a watch or from an api callback

I think you can add a property id to your user object.
And a property userId to your post object to avoid mistakes.
User has to be a prop of your element to be used into it

Related

Vuejs how to pass component data from caller

My main page renders a list of data coming from controller with foreach
#foreach ($sales as $sale)
<button id="{{$sale->id}}" #click="editClicked({{$sale}})">
#endforeach
I have an edit component placed on the page like this, I display it modally via showEditModal conditional
<edit v-if="showEditModal" #hide="showEditModal=false"></edit>
The component in brief is declared in Edit.vue:
<template name="edit">
...
</template>
This is simply a standard form with input fields, bound via v-model to the sale.
Essentially it is an update form, I intend to load the data from the main page into each input field to be edited.
My app.js simply sets showEditModal = true, in order to display the edit form on top of the main page.
Basically i don't want to have to call controller via GET method on loading the modal since i already have the data in the main page as $sale object, so im just wondering how do I pass in the $sale to the Edit.vue component ?
I thought that in the <edit> component usage, it would need to bind the sale object, however I'm unsure how that would work since it comes from the foreach loop.
I do, also have the data in the app.js method as passed in via #click="editClicked({{$sale}})", but again, i'm unsure how to use that to pass through ?
You're right, you would want to pass the current sale item as a property to the edit modal. What I would do is add a data property to your main Vue called selectedSale.
data:{
selectedSale: null
}
Then in your editClicked method, set selectedSale
methods:{
editClicked(sale){
this.selectedSale = sale
...
}
}
Finally, pass it as a property.
<edit :sale="selectedSale" v-if="showEditModal" #hide="showEditModal=false"></edit>

How to properly pass data from PHP to JS

I'd like to store a Customer model in a JS variable as JSON. Here are the approaches I tried and the pitfalls I found in each of them:
{{ $customer }} makes the resulting code in <script> look like this: var customer = {"id":1, ... "}, failing with Uncaught SyntaxError: Unexpected token & error. Also, if the variable is null in PHP, then in JS it becomes var customer = ;, which breaks the code.
{!! $customer !}} stores the data properly var customer = {"id":101, ... }, but it suffers from the same problem as {{ }} above when the variable is null in PHP.
{!! json_encode($customers->toArray()) !!}; works for a collection, but not for a single model object -- in the latter case PHP would fail by trying to call toArray() on null. Also, {!! !!} are vulnerable to XSS attacks.
The one that did work for me was {!! $customer ?? 'undefined' !!}. It properly handles all cases, but it's haky and insecure. Another solution seems to be {!! json_encode($customer) !!} but again, it also suffers from security issues. I wonder if it can be simplified to just {{ }}, or maybe there is a better approach.
Thanks!
Well that's a little difficult I was trying that time ago, but the only thing that I did (is not the better approach) is this...
I asssigned the values into data tags example
<input type="hidden" data-customer="{{json_encode(custumer)}}">
Then I used javascript/JQuery to access to tha info in my script
try isset
#if(isset($custumer)){{ $custumer }}#endif
I'm using this package, which does the magic for you:
https://github.com/laracasts/PHP-Vars-To-Js-Transformer

Most efficient way to get a specific model from a collection in BLADE in Laravel

Hi im developing a site using Laravel and have some site data id like to keep track of such as facebook url, instagram url, address, phone number, etc. This information for this model is stored as a name and value in the DB, so example name:facebook and value:[facebook url here]. I know that i can retrieve all the models and get a collection, pass it to my view and loop through them, but id like a little more control to get specific models to use it where i need them on specific parts of the page. This is what I currently have it:
I have a model SiteMeta which i pass an instance to my view:
$site_meta = new \App\SiteMeta();
return view($page_string)->with('site_meta',$site_meta);
And in my SiteMeta Model:
public static function get($name)
{
return SiteMeta::where('name', '=', $name)->firstOrFail();
}
And then in my view im getting my specific model by its name:
<a target="_blank" href="{{$site_meta::get('Facebook')->value}}">
<i class="fa fa-facebook-official data-icon" aria-hidden="true"></i>
</a>
So my question is, is this the most efficient way to do it? Im doing this in various places on the contact page to display information like phone number and address and other site information which i feel like is a bit overload as it make a request to the database each time im doing sitemeta::get('name');
Is there a better way to get a specific one from the collection in BLADE? Thanks
I would pass it as an array from your controller method:
$site_meta = \App\SiteMeta::lists('value', 'name');
return view($page_string, compact('site_meta');
On your blade template you could do this:
$site_meta['Facebook'];

Laravel 4 - Showing edit form with OLD data input as well as DB information

Im making a edit form for my app and i was wondering if someone could tell me how to get the data from the database into my text field.
I can locate the record i need to edit based on the users click, and i can display the information if i do the following:
value="{{ $letter->subject }}"
BUT, the problem im having is that when i run it through the validation and there is an error, it comes back with the database information instead of the OLD data.
So my questions is. Is there a way to serve up the database information first and then when it goes through the validatior, validate the information the user has edited?
Currently to validate the text field and bring the data back incase of error, im using
Input::old('subject')
Is there a parameter for that old bit that allows me to put in the DB data?
Cheers,
Hey you could validate and return ->withInput() and then in your actual form, check if there is Input::old() and display it, otherwise display from the db.
example:
<input type="text" name="subject"
value="{{ (Input::old('subject')) ? Input::old('subject') : $letter->subject }}">
Or you could go the other way and define the variable and do a regular if statement, instead of the ternary one! Up to you to decide what you want to use!
All you need is form model binding http://laravel.com/docs/html#form-model-binding:
{{ Form::model($letter, ['route' => ['letters.update', $letter->id], 'method' => 'put']) }}
// your fields like:
{{ Form::text('someName', null, ['class' => 'someHTMLclass' ...]) }}
// no default values like Input::old or $letter->something!
{{ Form::close() }}
This way you form will be populated by the $letter data (passed from the controller for example).
Now, if you have on your countroller:
// in case of invalid data
return Redirect::back()->withInput();
then on the redirect your form will be repopulated with input values first, not the original model data.
Make it more simple and clean
<input type="text" name="subject" value="{{ (Input::old('subject')) ?: $letter->subject }}">
I'm not sure for Laravel 4 but in Laravel 5, function old takes second param, default value if no old data in session.
Please check this answer Best practice to show old value

Form select box in Backbone Marionette

I'm trying using Backbone.Marionette to build an application. The application gets its data through REST calls.
In this application I created a model which contains the following fields:
id
name
language
type
I also created an ItemView that contains a complete form for the model. The template I'm using is this:
<form>
<input id="model-id" class="uneditable-input" name="id" type="text" value="{{id}}"/>
<input id="model-name" class="uneditable-input" name="name" type="text" value="{{name}}" />
<select id="model-language" name="language"></select>
<select id="model-type" name="type"></select>
<button class="btn btn-submit">Save</button>
</form>
(I'm using Twig.js for rendering the templates)
I am able to succesfully fetch a model's data and display the view.
What I want to do now is populate the select boxes for model-language and model-type with options. Language and type fields are to be restricted to values as a result from REST calls as well, i.e. I have a list of languages and a list of types provided to me through REST.
I'm contemplating on having two collections, one for language and one for type, create a view for each (i.e. viewLanguageSelectOptions and viewTypeSelectOptions), which renders the options in the form of the template I specified above. What I am not sure of is if this is possible, or where to do the populating of options and how to set the selected option based on data from the model. It's not clear to me, even by looking at examples and docs available, which Marionette view type this may best be realized with. Maybe I'm looking in the wrong direction.
In other words, I'm stuck right now and I'm wondering of any of you fellow Backbone Marionette users have suggestions or solutions. Hope you can help!
Create a view for a Select in my opinion is not needed in the scenario that you are describing, as Im assuming that your languages list will not be changing often, and the only porpouse is to provide a list from where to pick a value so you can populate your selects in the onRender or initializace function of your view using jquery.
you can make the calls to your REST service and get the lists before rendering your view and pass this list to the view as options and populate your selects on the onRender function
var MyItemView = Backbone.Marionette.ItemView.extend({
initialize : function (options) {
this.languages = options.languages;
this.typeList = options.typeList;
},
template : "#atemplate",
onRender : function () {
this.renderSelect(this.languages, "#languagesSelect", "valueofThelist");
this.renderSelect(this.typeList, "#typesSelect", "valueofThelist")
},
renderSelect :function (list, element, value) {
$.each(list, function(){
_this.$el.find(element).append("<option value='"+this[value]+"'>"+this[value]+"</option>");
});
}
})
var languagesList = getLanguages();
var typeList = getTypesList();
var myItemView = new MyItemView({languages:languagesList,typeList :typeList });
Hope this helps.

Resources