Laravel how to retrieve name with user_id using angular? - javascript

I'm only able to fetch data with title and body attribute, but when i get data for the name it shows up empty when i refresh the page but shows when i submit automatically.
For some reason angularjs is not retrieving the name successfully.
Note: I'm using laravel.
For example here:
Here is the server side:
PostController
public function getPosts() {
$posts = Post::with('user')->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function storePost(Request $request) {
$data = request()->validate([
'title' => 'required|max:120',
'body' => 'required|max:1000'
]);
$data['user_id'] = auth()->user()->id;
$data['name'] = auth()->user()->name;
$post = Post::create($data);
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
// return redirect('/home')->withMessage('A new post was created.');
return $response;
}
main.js
$scope.myposts = {};
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};
$scope.deletePost = function(post) {
var index = $scope.myposts.indexOf(post);
if (index != -1) {
$scope.myposts.splice(index, 1);
}
$http.delete('auth/post/' + post.id);
};
$scope.getPosts = function() {
$http.get('/auth/posts').then(function(data) {
$scope.myposts = data.data;
}).then(function(data, status, header, config) {});
};
HTML:
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading">
<% post.title %>
</div>
<div class="panel-body panel">
<figure>
<p>
<% post.body %>
</p>
by:
<p>
<% post.user.name %>
</p>
</figure>
<span><button ng-click="deletePost(post)">x</button></span>
</div>
</div>
When i first add content without refresh(asynchronously)
on page refresh
above
(different log for different post)

Your reload page is okay since
$posts = Post::with('user')->get();
returns
{
"title": "title",
"body": "body",
"user": {
"name": "name"
}
}
and in your angular you display it by
<% post.user.name %>
So the solution to display it when you added is to restructure your json object before pushing to array
$scope.addPost = function() {
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
console.log(data);
data.data['user'] = {
name: data.data.name
}
$scope.myposts.push(data.data);
});
$scope.post.title = '';
$scope.post.body = '';
};

Related

Angular JS send html to data base

I m sending html < p >hello< /p>
<div class="input-field">
<input id="price" type="number" ng-model="productData.price" ng-init="productData.price = ''" >
<label for="price">Price</label>
</div>
<div id="editor3" class="ql-container ql-snow">
<div class="ql-editor" data-gramm="false" contenteditable="true">
<p>hello</p>
</div>
</div>
<input type="hidden" ng-model="productData.description">
to angular js code, But it is not working. I am new to angular js. the fifth line below I thing not taking data from HTML code
$scope.addProdcut = function (productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": productData,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}
Controller file
public function addProduct()
{
if ($this->request->is('post')) {
$content = $this->request->input('json_decode', true);
$data = $content['data'];
$file = '';
if ($content['image'] != '') {
$file = date('ymd') . time() . '.' . 'jpg';
$path = WWW_ROOT . 'img/products/' . $file;
$this->base64_to_jpeg($content['image'], $path);
}
$products = TableRegistry::get('Products');
$query = $products->query()->insert(['item', 'price', 'description', 'image', 'status', 'added_by', 'created'])
->values([
'item' => $data['name'],
'price' => $data['price'],
'description' => $data['description'],
'image' => $file,
'status' => 1,
'added_by' => $this->loggedInUser['id'] . '||' . $this->loggedInUser['username'],
'created' => date("Y-m-d\TH:i:s"),
])->execute();
echo json_encode(['status' => 'success']);
exit;
}
}
it is a word editor in form, from where I want to save HTML code (from word editor) in data base using a hidden input field. by sending data ng-model to that hidden input field
You are storing the value in $scope.productData.description and then sending productData, instead, you should send $scope.productData.description.
$scope.addProdcut = function(productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": $scope.productData.description,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}

Output from controller to HTML form

Can someone please tell me how to output data from my controller to an HTML form. I want to change the label of an anchor from "Like" to "Liked" if the user has already clicked the link previously.
Here is the HTML.
<section class="row posts">
<div class="col-md-6 col-md-3-offset">
<header><h3>other posts</h3></header>
#foreach($posts as $post)
<article class="post">
<p>{{ $post->content }}</p>
<div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
<div class="interaction">
Like
#if(auth()->user() === $post->user)
|
Edit |
Delete
#endif
</div>
</article>
#endforeach
</div>
<script>
var token = '{{ session()->token() }}';
var urlLike = '{{ route('like') }}';
</script>
</section>
The JavaScript to get the postid from the form:
...
$('.like').on('click', function (event) {
event.preventDefault();
postId = event.target.dataset.postid;
var isLike = event.target.previousElementSibling==null ? true:false;
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike, postId: postId, _token: token}
})
.done(function () {
//change the page
})
})
...
The route:
Route::post('/like',[
'uses' => 'PostController#postLikePost',
'as' => 'like'
]);
Finally, can someone please tell me how to send the output from the controller to the HTML form?
public function postLikePost(Request $request)
{
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true' ? true : false;
$post = Post::find($post_id);
if (!$post) {
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id', $post_id)->first();
if ($like) { // user already liked the post
$like->delete();
return null; // output to "Like" in the html form here
}
$like = new Like();
$like->post_id = $post->id;
$like->user_id = $user->id;
$like->save(); // output to "Liked" in the html from here
return null;
}
The label of the Like anchor should change from Like to Liked if the user has already like the post.
I'd set up both as POSTs and then in your success block query the result and set to either like or liked. Something like:
success: function (data) {
document.getElementById("something").innerHTML = "Liked";
}
You can do it something like this, change it as per your need though.
public function postLikePost(Request $request)
{
$post = Post::where('id', $request->get('post_id'))->first();
if(!$post){
return response()->json(['status' => 1, 'message' => 'post not found']);
}
if($post->liked == 1)//change it as per your model
{
return response()->json(['status' => 2, 'message' => 'already liked']);
}
$post->status = 1;
$post->save();
return response()->json(['status' => 3, 'message' => 'liked']);
}
and in your ajax success
success: function(response){
if(response.status == 1){
window.alert('Post Not Found')
}
else{
document.querySelector('#likeBtn').innerHTML = 'liked'
}
like button
Like

how do you pass post id in angular?

How do you pass in the post id in angular if your using laravel ?
this is what i currently have, i tried referencing this
https://docs.angularjs.org/api/ng/service/$http
but im not really understanding.
Main.js
$scope.like = function() {
var post = {
// this doesn't work and i dont know how to pull in the post id.
id: "<% $post->id %>"
};
$http.post('post/like/'+ post).success(function(result) {
checkLike();
});
};
function checkLike(){
var post = {
id: "<% $post->id %>"
};
$http.get('post/'+ post '/islikedbyme').success(function(result) {
if (result == 'true') {
$scope.like_btn_text = "Delete Like";
} else {
$scope.like_btn_text = "Like";
}
});
};
Route
Route::get('post/{id}/islikedbyme', 'PostController#isLikedByMe');
Route::post('post/like', 'PostController#like');
Controller
public function isLikedByMe($id)
{
$post = Post::findOrFail($id)->first();
if (Like::whereUserId(Auth::id())->wherePostId($post->id)->exists()){
return 'true';
}
return 'false';
}
public function like(Post $post)
{
$existing_like = Like::withTrashed()->wherePostId($post->id)->whereUserId(Auth::id())->first();
if (is_null($existing_like)) {
Like::create([
'post_id' => $post->id,
'user_id' => Auth::id()
]);
} else {
if (is_null($existing_like->deleted_at)) {
$existing_like->delete();
} else {
$existing_like->restore();
}
}
}
this work i got the post id by using ng-init to pass in post id.
Html
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts ">
<div id="eli-style-heading" class="panel-heading"><% post.user.name %></div> // i need someway to pull in the post id. so i used ng-init not sure if this best practices.
<div class="panel-body panel" ng-init="getL(post)">
<i style="color:tomato; float:right; font-size:24px;" ng-click="like(post)" class="glyphicon glyphicon-heart"></i>
<figure>
<p ng-model="post.body" editable-text="post.body" e-form="textBtnForm"> <% post.body %></p>
<p name="created_at" ng-model="post.created_at"> <% post.user.created_at | phpDate : "human" %></p>
</figure>
<span>
<i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)" ng-if="post.deletable"></i>
<button ng-if="post.update" class="btn btn-default" ng-click="textBtnForm.$show()" ng-hide="textBtnForm.$visible">
Edit
</button>
<span><button ng-if="post.update" type="submit" class="btn btn-primary" ng-click="updatePost(post)">Update</button></span>
</span>
</div>
</div>
Main.js
$scope.like = function(post) {
$http.post('/post/like/'+ post.id).then(function(result) {
getL();
});
};
$scope.getL = function(post){
$http.get('/post/'+ post.id +'/islikedbyme').then(function(result) {
if (result == 'true') {
$scope.like_btn_text = "Delete Like";
} else {
$scope.like_btn_text = "Like";
}
});
}
Route
Route::get('post/{id}/islikedbyme', 'PostController#isLikedByMe');
Route::post('post/like/{post}', 'PostController#like');
Post Controller
public function like(Post $post, Request $request)
{
$existing_like = Like::withTrashed()->wherePostId($post->id)->whereUserId(auth()->id())->first();
if (is_null($existing_like)) {
Like::create([
'post_id' => $post->id,
'user_id' => auth()->user()->id
]);
} else {
if (is_null($existing_like->deleted_at)) {
$existing_like->delete();
} else {
$existing_like->restore();
}
}
}

Get the article's view times using Vue.js and Laravel 5.3

My thought process:
When the show page opens, get the article's id with JavaScript.
Check this id exist or not in cookie
If not exists, write it into cookie and send an ajax request, the backend updates view times.
If exists, do nothing.
Demo:
View:
<div class="card">
<div class="card-block text-xs-center">
<h5 class="card-title">{{$article->title}}</h5>
<hr class="m-y-2">
<h6 class="card-subtitle text-muted">date:{{$article->created_at->format('Y-m-d')}}
    views:{{$article->view_times}}</h6>
</div>
<div class="card-block">
<p class="card-text">{{$article->content}}</p>
</div>
</div>
Controller:
class ArticlesController extends Controller
{
//`show` method
public function show($id)
{
$article = Article::findOrFail($id);
return view('show', compact('article'));
}
//the method of updating view times.
public function statistics(Request $request)
{
$id = $request->input('id');
$article = Article::findOrFail($id);
$view_time=$article->view_time;
$article->view_time=$view_time+1;
$article->save();
}
}
JavaScript:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name=csrf-token]').getAttribute('content')
Vue.http.options.emulateJSON = true;
var vm = new Vue({
el: "body",
data: function(){
return{
id:[]
}
},
created() {
//1、Get the article's id.Do I have to send an ajax request? Is there any other way?
this.$http.get('article/get-id').then((response) => {
// success callback
this.id=response.data;
}, (response) => {
// error callback
});
//2、After Getting the `id`,check it in cookie,I don't know how to do it?
//3、If not exists,write it into cookie and send an ajax request,how to write the if() sentence?
if(){
var formData = new FormData();
var id=this.id;
formData.append('id',id);
this.$http.patch('article/statistics', formData,{
before(request) {
if (this.previousRequest) {
this.previousRequest.abort();
}
this.previousRequest = request;
}
}).then((response) => {
// success callback
}, (response) => {
// error callback
});
}
}
});
Questions:
There are three questions, shown as comments in JavaScript code above.

AngularJS configuring the persistence layer interaction

I currently have a very simple application which initially calls a php file to get data and then iterate through the dataset and create a table. Within the table I have an "Enable/Disable" button which when clicked would update the model, which in turn would push to the persistence layer. The issue I am running into is that while I am able to update the model which updates the view nicely, I am unable to figure out how to get the persistence layer part of it working. I added two custom functions for the service "enable/disable" to reflect the button click event, but am not really sure if I am heading in the correct direction or not but my code is below.
The View partial:
<table class="table table-hover">
<thead><tr><th>Name</th><th>Username</th><th>Details</th><th>Facility</th><th>Last Login</th><th>Days from last login</th></tr></thead>
<tbody>
<tr ng-class="{'error':user._accountDisabled,'success':user._accountDisabled==false}" ng-repeat="user in users | filter:query | orderBy:orderProp">
<td>{{user._firstName}} {{user._lastName}}</td>
<td>{{user._userName}}</td>
<td><a class="btn btn-primary" href="#/userExceptions/{{user._userName}}">Details</a></td>
<td>{{user._facilityName}}</td>
<td>{{user._hrLastLogon}}</td>
<td>{{user._daysLastLogon}}</td>
<td>
<ng-switch on="user._accountDisabled">
<button ng-switch-when=true class="btn btn-primary" ng-click="enable(user)">Enable</button>
<button ng-switch-when=false class="btn btn-danger" ng-click="disable(user)">Disable</button>
</ng-switch>
</td>
</tr>
</tbody>
</table>
The custom service for persistence:
angular.module('userServices', ['ngResource']).
factory('User', function($resource) {
return $resource('userActions.php', {}, {
query: {method: 'GET', params: {userName: 'userName'}, isArray: true},
enable: {method: 'GET',params: {action: 'enable', userName: 'userName'}}},
disable: {method: 'GET', params: {action: 'disable', userName: 'userName'}}
});
});
Finally the controller:
function UserExceptionsCtrl($scope, User) {
$scope.users = User.query();
$scope.orderProp = '_firstName';
$scope.enable = function(user) {
$scope.user = user;
$scope.user._accountDisabled = false;
$scope.user.$save();
User.enable({userName:user._userName});
};
$scope.disable = function(user) {
$scope.user = user;
$scope.user._accountDisabled = true;
$scope.user.$save();
User.disable({action: 'disable', userName: self._userName});
};
}
EDIT As requested server side code:
The useractions file processes the request and creates mappers to retrieve a user object. From the user object it updates the necessary property and saves it in the persistence layer.
userActions.php
$username = (isset($_REQUEST['userName']) ? $_REQUEST['userName'] : '');
$action = (isset($_REQUEST['action']) ? $_REQUEST['action'] : '');
require 'library/autoloader/src/autoload.php';
try {
$ADUserMapper = new UserMapper(new LDAPAdapter());
switch ($action) {
case 'enable':
$ADUserEditMapper = new UserMapper(new LDAPAdapter());
$user = $ADUserEditMapper->findByUsername($username);
if ($user) {
$user->enableADAccount();
$ADUserEditMapper->updateUAC($user);
}
break;
case 'disable':
$ADUserEditMapper = new UserMapper(new LDAPAdapter());
$user = $ADUserEditMapper->findByUsername($username);
if ($user) {
$user->disableADAccount();
$ADUserEditMapper->updateUAC($user);
}
break;
default:
$adapter = new PdoAdapter();
$employeeDBMapper = new EmployeeMapper($adapter);
$ADUsers = $ADUserMapper->findMultipleUsers(array('objectClass' => 'user'), "OU=Users,DC=domain,DC=com", TRUE);
$exceptions = array();
foreach ($ADUsers as $user) {
$employee = $employeeDBMapper->findByUserName($user->userName);
if (!$employee) {
array_push($exceptions, $user);
}
}
$result = array();
foreach ($exceptions as $user) {
array_push($result, $user->getExceptionData());
}
echo json_encode($result);
break;
}
} catch (Exception $e) {
echo json_encode(array('error' => true, 'errorMessage' => $e->getMessage()));
}

Categories