Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this
var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js
example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK
Controller
class SearchCompanyName extends Controller
{
public function getcompanyname($name)
{
return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
}
public function index()
{
$url = $this->getcompanyname(Input::get("company_name_by_user"));
return view('searchcompany', ['url' => $url]);
}
}
vue app.js
Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
el: '#search',
data: {
},
method: {
getMessages: function(){
console.log('I am here')
}()
}
});
blade template
#section('content')
<div class="container">
{!! $url !!}
<search></search>
</div>
#endsection
If you want to declare your javascript variable in a script tag within a blade file, you need to put the variable in quotes like so
<script>
var url = '{{ $url }}';
</script>
You can use this package : https://github.com/laracasts/PHP-Vars-To-Js-Transformer
public function index()
{
JavaScript::put([
'foo' => 'bar',
'user' => User::first(),
'age' => 29
]);
return View::make('hello');
}
Related
there is a way to listen the laravel livewire lifecycle hooks? for example...
in php is:
public function updatedFoo($value)
{
//
}
how it can be in js (i know use #this generate the id finder)?
window.Livewire.find('componentIdGenerated').on('updatedFoo', function(value) {
//
});
thanks a lot!
It's possible and really cool. As the documentation tells, there is JavaScript hooks related like
<script>
document.addEventListener("DOMContentLoaded", () => {
....
Livewire.hook('message.sent', (message, component) => {})
Livewire.hook('message.failed', (message, component) => {})
Livewire.hook('message.received', (message, component) => {})
Livewire.hook('message.processed', (message, component) => {})
});
</script>
Let's say, you make some call to some method and using this you can get messages hooks and do proper operations
<script>
document.addEventListener("DOMContentLoaded", () => {
Livewire.hook('message.sent', (message,component) => {
if (message.updateQueue[0].payload.method === 'openModal') {
// message was sent
}
Livewire.hook('message.received', (message,component) => {
if (message.updateQueue[0].payload.method === 'openModal') {
// message was received
}
// and go on!
</script>
also you can listen when an event occurs and do the same
<script>
document.addEventListener("DOMContentLoaded", () => {
Livewire.hook('message.sent', (message,component) => {
if (message.updateQueue[0].payload.event === 'someDispatchedEvent') {
// message was sent
}
Livewire.hook('message.received', (message,component) => {
if (message.updateQueue[0].payload.event === 'someDispatchedEvent') {
// message was received
}
// and go on!
</script>
hope you can exploit this more and show us how you go! ;-)
thanks to #Prospero for give the first steps and the general idea about the necesary code
first we need to save the initial state of our property (in my case is a modal component, the id is dynamic):
The variables in brackets are blade variables)
...
#php
$id = $id ?? \Illuminate\Support\Str::random(15);
$model = $attributes->wire('model')->value()
#endphp
...
<script wire:ignore>
var model{{ $id }};
document.addEventListener("livewire:load", function(event) {
model{{ $id }} = #this.{{ $model }};
});
</script>
then, with the livewire hooks, you have to listen the element.updated event, and compare the initial state with the new state of the livewire property
i use only conditional comparisons, i saw you can use Proxy for clean code:
<script wire:ignore>
document.addEventListener("DOMContentLoaded", () => {
Livewire.hook('element.updated', (el, component) => {
if(model{{ $id }} && !#this.{{ $model }})
new bootstrap.Modal(document.getElementById('{{ $id }}')).hide();
if(!model{{ $id }} && #this.{{ $model }})
new bootstrap.Modal(document.getElementById('{{ $id }}')).show();
model{{ $id }} = #this.{{ $model }};
});
});
</script>
I use this for open a bootstrap modal blade component component.
I'm trying to build a simple website builder that allow users to save their generated html created with Vue component and see it at a certain URL.
Because of it I have to store and retrieve the html generated but I have some problems with retrieving of the code. Here is my step:
When user click "save" this function is fired, that select the portion of HTML that include the "website" built by the user:
saveBuilders: function () {
let pages = [];
let builders = $('[id*="builder-container-"]');
$.each(builders, function (key, builder) {
let singleElem = $(builder).attr('id');
pages.push(clearElement.html());
});
this.storeInDb(pages);
},
storeInDb: function (pagesList) {
axios.post("/landing-page/store", {
name: this.name,
description: this.description,
html: pagesList
})
.then(function (response) {
console.log('Cool');
})
.catch(function (error) {
console.log('ERROR', error.response);
});
},
The Axios request is handled by this function that store the html portion in DB
public function store(Request $request)
{
$data = $request->all();
$html = $data['html'];
$landingPage = new LandingPage();
$landingPage->name = $data['name'];
$landingPage->description = $data['description'];
$landingPage->user_id = Auth::user()->id;
$landingPage->html = json_encode($html);
try {
$landingPage->save();
return 'true';
} catch (exception $e) {
return $e;
}
}
Now when the user visit a certain URL, for keep thing simple suppose is example.it/website/0, this function is fired:
public function show($landing_id)
{
try {
$landingPage = LandingPage::where([
'id' => $landing_id,
'user_id' => Auth::user()->id
])->first();
} catch (\Exception $e) {
$landingPage = null;
}
if ($landingPage != null) {
//GET THE HTML
$page = json_decode($landingPage->html);
return view('landing_page.show')->with('page', $page)
} else {
abort(404, 'Error');
}
}
And this the blade where I'm trying to re-create the Vue.js environment
<body>
<span id="countdown"></span>
<div id="builder-pagina">
<builder>
{!! $page !!}}
</builder>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="{{asset('js/landing_page/app.js')}}"></script>
</body>
</html>
I thought that having the html generated by vue similar to something like that into the DB...
<div data-v-29b64d26="" >
<h1>This piece of code was stored into my DB</h1>
<div data-v-56f62f0a="">
</div>
</div>
...you could create everything working simply by pasting the code and by using the same js file used for compiling vue.js.
I've tried pass the entire code by props but is not working. Also tried with slot. Any suggestions?
am trying to retrieve data from a database using vuejs ajax call with a plugin called vue-resource. Unfortunately, the json data object contains the html page and not the actual data from the database. Can someone please tell me what am doing wrong?
This is my code:
routes.php
<?php
Route::get('find', 'FruitsCtrl#index');
fruitsctrl.php (controller)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Fruit;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome', $fruits);
}
}
fruit.php (model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Fruit extends Model
{
protected $fillable = [
'id', 'name', 'type'
];
}
fruitshome.blade.php (view)
<head>
<meta id="token" content="{{ csrf_token() }}">
</head>
<body>
<div class="row" id="vapp">
<ul>
<li v-for="fruit in fruits">
#{{ fruit.name }}
#{{ fruit.type }}
</li>
</ul>
</div>
<body>
app.js (javascript)
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
var v = new Vue({
el : "#vapp",
ready :function () {
this.fetchFruits();
},
data : {
fruit : {id:'', name:'', type:''},
fruits : []
},
methods : {
fetchFruits : function(){
this.$http.get('/find').then(function(res){
this.fruits = res;
},function (data){
console.log(error ...);
});
}
}
});
You're currently returning a view from your controller:
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome', $fruits);
}
}
Instead, you can return the Eloquent results directly and they'll be output as JSON:
class FruitsCtrl extends Controller
{
public function index(Request $req){
$fruits = Fruit::all();
return $fruits;
}
}
I think you need to set table name in the model like this :
class Fruit extends Model
{
protected $table = 'fruits';
protected $fillable = [
'id', 'name', 'type'
];
}
You also need to update index method like this :
public function index(Request $req){
$fruits = Fruit::all();
return view('fruitsHome')->withFruits($fruits);
}
and finally update the blade :
<li v-for="fruits in fruit">
#{!! $fruits->name !!}
#{!! $fruits->type !!}
</li>
Let me know if it helps you
Why function return full html code in console. How return only data(div block)?
HTML
How return data only this block
<div class="message_box">
#foreach(json_decode($message) as $content)
{{ $content->message }}
#endforeach
</div>
AJAX
$(function () {
$.get('chat', function(data){
console.log(data);
});
});
Controller
public function chat()
{
$user = User::all();
$message = MessageModel::orderBy('id')->get();
return view('chat.chat', ['user' => $user, 'message' => json_encode($message)]);
}
Result prtscreen here
This problem occurs when you extend layout
If you are using Laravel 5 you should check in your view if you have any #extend directive in blade file or if you are using Laravel 4 you should also check in your controller that if you have any $layout property
Here you are returning html
return view('chat.chat', ['user' => $user, 'message' => json_encode($message)]);
Now if you want to return this as JSON response you have render the HTML & then return the response as an array like this
return ['html' => view('chat.chat', ['user' => $user, 'message' => json_encode($message)])->render()];
I can save all data varchar/text element from my form, but I can't save my path image.
Whats is wrong with my code?
Lets see my create.blade.php I can save value of var deadline but I can't save value of var path:
Form::open(array('url' => 'imagesLoker', 'files' => true))
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
{!!Form::label('Deadline Lowongan : ')!!}
{!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
</div>
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('path') !!}
</div>
</div><!-- /.box-body -->
</form>
{!!Form::close()!!}
This is my Controller:
public function store(Request $request)
{
Lowongan::create($request->all());
return "data all";
}
This is my Ajax to create the data:
$("#createLoker").click(function(){
var datas = $('form').serializeArray();
var route = "http://localhost:8000/lowongan";
var token = $("#token").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post(route,{
deadline: $("#deadline").val(),
path: $("#path").val()
}).done(function(result){
console.log(result);
});
});
I don't know this is important or no to setting parse data in my Modal, but I just put this code in my Modal:
class Lowongan extends Model
{
protected $table = 'Lowongan';
protected $fillable = ['path','deadline'];
public function setPathAttribute($path){
$this->attributes['path'] = Carbon::now()->second.$path->getClientOriginalName();
$name = Carbon::now()->second.$path->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($path));
}
}
And the last I set the directory to save the image. This is setting in the config/filesystem:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imagesLoker'),
],
I can save the data deadline but no for image :( .. If there is any idea for how to save the image path, I will be pleased to know it.
In your form you have to allow file upload option in laravel like.
Form::open(array('url' => 'foo/bar', 'files' => true))
check the file upload section of laravel doc
Hope it helps..
please follow these steps
in view
change {!!Form::file('path') !!} to {!!Form::file('file') !!}
In controller
please note i have set the upload path to root/public/uploads/ folder
public function store(Request $request)
{
$file = Input::file('file');
$path = '/uploads/';
$newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
// Move the uploaded file
$upSuccess = $file->move(public_path() . $path, $newFileName);
$result = file_exists(public_path() . $path . $newFileName);
$fileData =[
'fileType' => $file->getClientOriginalExtension(),
'filePath' => substr($path, 1) . $newFileName
];
Input::merge(array('path' => $fileData["filePath"]));
Lowongan::create($request->all());
return "data all";
}