send pusher notification to specific user - Laravel - laravel

In my laravel app, I want to send a notification to a specific user using Pusher.
I put this code in my method :
$pusher = App::make('pusher');
$pusher->trigger( 'notification-channel',
'notification-event',
array('text' => 'this is a notification'));
return view('home');
and put this in home.blade.php :
<script src="//js.pusher.com/3.0/pusher.min.js"></script>
<script>
var pusher = new Pusher("{{env("PUSHER_KEY")}}");
var channel = pusher.subscribe('notification-channel');
channel.bind('notification-event', function(data) {
alert(data.text);
});
but this makes notification to appear to any user.
This also has another problem that the user should be only on the home page to receive the notification!
So, what should I do to send a notification to a specific user and make the user receive it from any page ??

To make the user receive it from any page, put your Pusher code in your layout.blade.php if you have any. Or any other file that all pages will extends.
To make it go to a specific user, you can use the user id by appending it to the channel like
'notification-channel:' . $user->id
So in your layout file you listen to that channel
var user = <?php echo $user ; ?>;
var channel = pusher.subscribe('notification-channel:' + user.id);
Although only user with that easy might receive the notification, your notification remains public. Meaning anyone can manipulate their id and receive someone else notifications. If you want private notifications, you can follow instructions here: https://laravel.com/docs/5.4/broadcasting#authorizing-channels

Related

Laravel 5.6 Like Button

I'm using this package here in Laravel 5.6 to add likes system in my project.
I have updated the models as per their documentation. However, I'm confused on how to use this package.
I have added tried the following which adds the logged in user to the particular article likes list when he visits the link.
public function show(ArticleCategory $articlecategory, $slug)
{
$categories = ArticleCategory::all();
$article = Article::where('slug', $slug)->first();
$user = User::first();
$user->addFavorite($article);
return view('articles.show', compact('article', 'categories'));
}
And in my user dashboard, I'm able to pull up all the articles which are liked by the user with
$user = Auth::user();
$favoritearticles = $user->favorite(Article::class);
But I'm looking for a functionality where I have a button on the article page where when a logged user clicks on it, he is added to the likes list. I haven't tried this before so stuck at this point.
I replaced
$user->addFavorite($article);
with
$user->toggleFavorite($article);
but that just toggles the favourite list. I mean when I visit the link once, the logged in user is added to the likes list. When I visit the link for the second time, the logged in user is removed from the likes list. The cycle is repeated.
Could anyone explain to me how to achieve the like functionality with a button?
you're almost there,
You have to add a button and on click you will trigger an AJAX request to the server to perform what you want without refreshing the page, here is an example:
First you'll add a button and give it an ID or class:
<button class="like">Like</button>
Then the moment you click on it, you'll call the url which you need to replace with the route to your function,
Then you have to declare a method like so:
public function like($slug)
{
$article = Article::where('slug', $slug)->first();
$user = \Auth::user(); //to get authenticated user...
$user->toggleFavorite($article); // toggle so if u already like it u remove it from the liked table
return response()->json(['status': 1])
}
And of course add the route to your routes.php:
Router::get('like/{slug}',"ArticleController#like");
then add the function (jQuery is used here) to hook the AJAX call
$('.like').on('click', function(){
$.ajax({
type: "GET",
url: 'wwww.example.com/articles/slug',
data: {slug: 'the slug'},
success: function(data){
alert('its done')
},
});
})
Create a form in you article page with a button
<form action="{{url('favorite/{$post->id}')}}" method="post">
#if($post->isFavorited())
<button type="submit">Remove from favorite</button>
#else
<button type="submit">Add to favorite</button>
#endif
</form>
create the favorite route and controller
Router::post('favorite/{id}',"ArticleController#toggleFavorite");
public function toggleFavorite($id) {
$article = ArticleCategory::find($id);//get the article based on the id
Auth::user()->toggleFavorite($article);//add/remove the user from the favorite list
return Redirect::to('article/{$id}');//redirect back (optionally with a message)
}

Laravel 5: Sending email with attached .pdf file generated from dynamic page

I have a job website. Job seeker users can register and build their profile (online resume), and it is used for one click application.
When job seekers logged in and click "Apply Now" button to any job, I want Laravel to send an email attached with .PDF resume (generated from their online resume building page) to employer's inbox.
Note: I do not want to send their uploaded resume (.pdf/.doc) to employer's inbox because I want to promote my website's branding / resume template.
Please tell me how to achieve this. If any source code provided, I would appreciated.
thank you.
You can use a html to pdf converter (something like http://github.com/barryvdh/laravel-dompdf). This will create the users profile in PDF format.
After the user clicked the button there will be an email sended to the employer with the attached pdf from the user.
It will look something like this:
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
$m->to($user->email, $user->name)->subject('Your Reminder!');
$m->attach($pathToFile);
});
And with custom mail per email:
Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
$m->from('hello#app.com', 'Your Application');
$m->to($user->email, $user->name)->subject('Your Reminder!');
$m->attach($pathToFile);
});
This will create the PDF, save it to the storage directory. You can use the views for the design:
public function createCollageCron($load_id) {
$load = Loads::findOrFail($load_id);
$pdf = PDF::loadView('pdf.collage', compact('load'));
if ($pdf->save(storage_path('app/loadings/'.$load->id.'/collage.pdf'))) {
return true;
} else {
return false;
}
}
Hope this works!

Redirect from method in Vue.js with Vue-router older than version 1.x.x

I'm not much of a frontend developer but I know enough javascript to do the minimum.
I'm trying to plug into a last piece of login however my vue components are:
"vue-resource": "^0.9.3",
"vue-router": "^0.7.13"
I'm not experienced enough to move up to v1 or v2 respectively.
I would like to achieve something similar to this.
However I'm not getting a successful redirect.
my app.js file:
var router = new VueRouter();
...
import Auth from './services/auth.js';
router.beforeEach(transition => {
if(transition.to.auth &&!Auth.authenticated)
{
transition.redirect('/login');
}
else
{
transition.next();
}
});
```
In my login.js file
```
methods: {
/**
* Login the user
*/
login(e) {
e.preventDefault();
this.form.startProcessing();
var vm = this;
this.$http.post('/api/authenticate',
{ email : this.form.email,
password : this.form.password
})
.then(function(response){
vm.form.finishProcessing();
localStorage.setItem('token', response.data.token);
vm.$dispatch('authenticateUser');
},
function(response) {
if(response.status == 401)
{
let error = {'password': ['Email/Password do not match']};
vm.form.setErrors(error);
}else{
vm.form.setErrors(response.data);
}
});
}
}
I tried to do as suggested:
vm.form.finishProcessing();
localStorage.setItem('token', response.data.token);
vm.$dispatch('authenticateUser');
vm.$route.router.go('/dashboard');
However all it did was append the url on top.
I see that the 3 previous events were successfully done but not the redirect.
it went from:
http://dev.homestead.app:8000/login#!/
to
http://dev.homestead.app:8000/login#!/dashboard
when I need the entire page to go to:
http://dev.homestead.app:8000/login/dashboard#1/
I think i have a missing concept in order to do the redirect correctly.
UPDATE
As per suggested i have added param: append => false but nothing happens.
what i did afterward was within app.js create a method called redirectLogin() with console.log() outputs - that worked. what i did further is i put vm.$route.router.go inside there and called the method via vm.$dispatch('redirectLogin'); and that also didn't work.
NOTE:
The HTML is being rendered in Laravel first. the route I originally had (and working) as login/dashboard and that route is available via normal Laravel route. the blade is being rendered via view template.
So far I've been trying to vue redirect over to login/dashboard (not working) perhaps I should somehow remove login/dashboard and use the route.map and assign login/dashboard?
I would rather keep the login/dashboard as a laravel route due to authentication and other manipulation.
For Vue 2
this.$router.push('/path')
As par the documentation, router.go appends the path in the current route, however in your case it is appending along with # in the router as well.
You can use param: append, to directly arrive at your desired destination, like following:
vm.$route.router.go({name: '/login/dashboard#1/', params: {append: false}})
Edited
If it is not happening, you can try $window.location method like following:
var url = "http://" + $window.location.host + "login/dashboard";
console..log(url);
$window.location.href = url;
I think their is a misunderstanding here of how vue-router works. It seems you are not wanting to load a new route with a corresponding component, rather you simply want to redirect to a new page then let that page load and in turn fire up a fresh instance of vue.
If the above is correct you don't need vue-router at all. Simply add the below when you need to load the page:
window.location.href = '/login/dashboard'
If you'd rather simulate a redirect to that page (no back button history) then:
window.location.replace('/login/dashboard')
EDIT
The above would be fired when you have finished all processing that the page must run to set the users state which the next page requires. This way the next page can grab it and should be able to tell the correct state of the user (logged in).
Therefore you'll want to fire the redirect when the Promise has resolved:
.then(function(response){
vm.form.finishProcessing()
// store the Auth token
localStorage.setItem('token', response.data.token)
// not sure whether this is required as this page, and in turn this instance of vue, is about to be redirected
vm.$dispatch('authenticateUser')
// redirect the user to their dashboard where I assume you'd run this.$dispatch('authenticateUser') again to get their state
window.location.replace('/login/dashboard')

Laravel Event w/ Javascript

I have a Laravel event set up to broadcast data to the client each time a user posts a comment and then I use javascript to append that data in the view. My issue is that if user1 posts a comment to user2's profile, I only want to append that data to user2's profile and not all profiles in general. So, in my event broadcast I pass through the ID of the profile the post was posted to (i.e. user2's ID).
Then I'm thinking I can do something like...
#if ($user->id === $id)
// Display appended data
#else
#endif
My problem is that I'm unsure how to properly check those two ID's. The $user->id references that profile's ID and then the $id is the profile ID sent through by the posted message. But I can't compare the two since the $id comes back through as a JSON object.
Should I just put the #if like this? If so, what's the correct syntax?
<script>
var pusher = new Pusher('03fe3c261638a67dbce5');
var channel = pusher.subscribe('newMessage');
channel.bind('Yeayurdev\\Events\\UserHasPostedMessage', function(data) {
#if ($user->id === $id)
// Display appended data
#else
#endif
});
</script>
Thanks!

How to determine the authorization in Joomla

After login i use need to set up redirect to custom page. How to catch this authorization in onAfterRoute event?
You should go to this path:
JOOMLAROOT/components/com_user/controller.php
in function register_save(), find this code:
if ( $useractivation == 1 ) {
$message = JText::_( 'REG_COMPLETE_ACTIVATE' );
} else {
$message = JText::_( 'REG_COMPLETE' );
}
after line put this code:
$this->setRedirect('/Your Custom Page Address', $message);
Why not just use the built in redirect in either the Joomla user login menu item or the standard Joomla login module. Both offer the option to redirect a user after a successful login. In the case of the module, you would need to create a menu item pointing to the custom page, but that's easy enough to do.
Is there something you need to do other than just a simple redirect? If not, then just use the system as it is designed.
I would create a small plugin that handles the redirect after login.
After a user has been logged in, the event onUserLogin is triggered, and you could simply do a redirect when the event is called.
Avoid any core hacks, since you'll allways end up having a hazzle during updates.
The code for a plugin like this could look like this:
class plgAuthenticationMyredirect extends JPlugin{
function onUserLogin ($user, $options){
$link = 'index.php?option=.....';
$msg = 'Message to show after login';
$app = JFactory::getApplication();
$app->redirect($link, $msg);
}
}

Resources