Laravel 5.6 Like Button - laravel

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)
}

Related

How to send information from the vue.js file to the controller like an id? Laravel - Inertia-vue

I'm trying to open a page from a button, but I need to send the id of the item where the button is in. For context this is a discussion forum page, in the users dash they are shown the forums they can comment on and there is a button on the bottom of each, what I need to send is that forums id, so that when they click on the button it takes them to the correct forum view.
How can I do this?
I'm trying different ways
<el-button type="primary" #click="submit(f.id)">
Answer
</el-button>
submit($id) {
var link = 'comments/' + $id;
this.$inertia.visit('comments/' + $id, {
$id,
});
},
<inertia-link class="el-button el-button--warning"
:href="'comments/' + f.id">
Answer
</inertia-link>
In my routes web.php
Route::resource('comments', 'ReplyController');
Route::get('comments/{id}', 'ReplyController#index');
The index in the controller
public function index($id)
{
$forum = DiscussionForum::where('id', $id)
->with('comment', 'user')->first();
$comment = Reply::with('discussionForum', 'user')
->where('discussion_forum_id', $forum->id)
->orderByDesc('updated_at')->get();
return Inertia::render('Forum/Comment.vue', [
'forum' => $forum,
'comments' => $comment
]);
}
This is not working, the redirect shows me a blank window inside the main page? How can I send the forum id correctly?
The best way to do this is to add a name to the route so:
Route::get('comments/{id}')->name('comments')->uses('ReplyController#index');
Then you can pass your id in the inertia-link in this way:
<inertia-link class="el-button el-button--warning"
:href="route('comments', { f.id })">
Answer
</inertia-link>
This way can be used with Ziggy as mentioned in the docs.
https://inertiajs.com/routing
Use the emit function here: https://v2.vuejs.org/v2/guide/components-custom-events.html
Something like this:
yourMethod() {
this.$emit(
"someName",
this.id
);
}

Difference between update and editing in controller - laravel

My table has the option edit. A row can be updated and saved to the database. While I was trying to implement this option I came across uncertainty. What do I have to do with the data from my edited row when it arrives at my controller? It doesn't seem clear to me do I have to use the edit, the update or combine them both? Do I need edit to find the id of the row that needs to be updated?
I am using the following code in methods to send data to my controller
<template slot="actions" slot-scope="row">
<span #click="updateProduct(row.item);" class="fas fa-pencil-alt green addPointer"></span>
</template>
updateProduct: async function(productData) {
axios.post('/product/update', {
productData: productData
.catch(function(error){
console.log(error)
})
})
}
In my controller, I think I have to find the id. I am pretty sure I am confusing different methods together. Thanks for any input.
public function edit()
{
$product = Product::with('id')->find($id);
// do something with it
}
public function update(Request, $request){
$product->update([
'name' => $request->productData->Name,
'description' => $request->productData->Descr
]);
}
the difference is significant. Edit is for displaying a form to apply changes and Update is used to set them up to server.
Edit is via GET http Update is via PUT http
In Laravel resource controller you can see these two functions "edit" & "update"
For example, you have a resource route 'post'
Edit:
you can return your edit form with your previously stored data
you can call using GET method & URL will be "/post/{id}/edit" and the route will be "post.edit"
update:
you can submit your data which you want to update
you can call using PUT/PATCH method & URL will be "/post/{id}" and the route will be "post.update"
For more information refer : laravel.com -> controllers

Laravel Sub-menu Within View

Hi I am very new to Laravel and MVC frameworks in general and am looking to create a list of links (in a view within a template) that links to some content. I am using this to display a list of nine people and to display their profile description when the link is clicked on. I have created a model of what the page looks like at http://i.imgur.com/8XhI2Ba.png. The portion that I am concerned with is in blue. Is there a way to route these links to something like /about/link2 or /about?link2 while maintaining the same exact page structure but modifying the ‘link content’ section (on the right of the link menu) to show the specific link's content? I would greatly appreciate it if someone could point me in the right direction, as I have literally no clue where to go with this!
There are a couple ways you can go about doing this.
Templates
Create your route.
Im assuming a lot about your app here but hopefully you get the picture. If you need help with anything in particular, be sure to update your question with the code youve tried so it will be easier to help you.
Route::get('about/{page}', function($page)
{
$profile = Profile::where('name', $page)->first();
return View::make('about')->with('profile', $profile);
});
Modify Template.blade.php
Put this line where you wish for About.blade.php to appear.
#yield('content')
Create your view which will extend your template
#extends('Template')
#section('content')
<h2>User Profile</h2>
<ul>
<li>Name: {{ $profile->name }}</li>
<li>Last Updated: {{ $profile->updated_at }}</li>
</ul>
#stop
AJAX
This solution will utilize AJAX to grab the data from the server and output it on the page.
Route for initial page view
Route::get('about', function($page)
{
$profiles = Profile::all();
return View::make('about')->with('profiles', $profiles);
});
Feel free to follow the same templating structure as before but this time we need to add some javascript into the template to handle the AJAX. Will also need to id everything which needs to be dynamically set so we can easily set it with jquery.
#extends('Template')
#section('content')
<h2>Links</h2>
#foreach($profiles as $profile)
{{ $profile->name }}
#endforeach
<h2>User Profile</h2>
<ul>
<li>Name: <span id="profile_name">{{ $profile->name }}</span></li>
<li>Last Updated: <span id="profile_updated_at">{{ $profile->updated_at }}</span></li>
</ul>
<script>
function setProfile(a)
{
$.ajax({
method: 'get',
url: 'getProfile',
dataType: 'json',
data: {
profile: $(a).data('id')
},
success: function(profile) {
$('#profile_name').html(profile.name);
$('#profile_updated_at').html(profile.updated_at);
},
error: function() {
alert('Error loading data.');
}
});
}
</script>
#stop
Route to handle the AJAX request
Route::get('getProfile', function()
{
$profile_id = Input::get('profile');
$profile = Profile::find($profile_id);
return $profile->toJson();
});
Now, the page should not have to reload and only the profile information should be updated.
Making some assumptions here as no code posted and assuming you're using the latest version of Laravel, Laravel 5.
Lets say you have a table in your database named users and you have a Model named Users (Laravel 5 comes with the Users model as default, see app/Users.php). The users will be the base of our data for the links.
Firstly, you want to register a route so you can access the page to view some information. You can do this in the routes file. The routes file can be found here: app/Http/routes.php.
To register a route add the following code:
Route::get('users', ['uses' => 'UserController#index']);
Now what this route does is whenever we hit the URL http://your-app-name/public/users (URL might be different depending on how you have your app set up, i.e. you may not have to include public) in our web browser it will respond by running the index method on the UserController.
To respond to that route you can set up your UserController as so:
<?php namespace App\Http\Controllers;
class UserController extends Controller {
public function index()
{
}
}
Controllers should be stored in app/Http/Controllers/.
Now lets flesh out the index method:
public function index()
{
// grab our users
$users = App\Users::all();
// return a view with the users data
return view('users.index')->with('users');
}
This grabs the users from the database and loads up a view passing the users data.
Here's what your view could look like:
<!DOCTYPE html>
<html>
<head>
<title>Users Page</title>
</head>
<body>
#foreach($users as $user)
<a href="{{ URL::route('user', ['id' => $user->id]) }}">
{{ $user->username }}
</a>
#endforeach
</body>
</html>
The view code will loop through each user from the $users data we passed to the view and create a link to their user page which is different for each user based on their id (their unique identifier in the DB)
Due to the way I've named it, this would be found in app/views/users/index.blade.php - if you save files ending in blade.php you can use Laravel's templating language, blade.
Now you need to finally set up another route to respond to a user page, for example http://your-app-name/public/user/22.
Route::get('user/{id}', ['uses' => 'UserController#show']);
Then add the show method to UserController
public function show($id)
{
// this will dump out the user information
return \App\User::find($id);
}
Hope that helps a little! Wrote most of it off the top of my head so let me know if you get any errors via comment.
This question is very bare, and it is difficult to actually help your situation without you showing any code. Just to point you in the right direction though, here is what you would need.
A Model called People, this is how you will access your data.
A controller. In this controller you will do the following
Get the ID of the profile you want from the functions parameters
Find that persons information e.g. People::find($person_id);
return the profile view with that persons data e.g. return view('profile')->with('person', $person);
In your view you can then use that data on that page e.g. {{ $person->name }}
For the page that needs to display the links to the people you would have a method in your controller which..
Get all the people data e.g. People::all();
Return a view with that data return view('all-people')->with('people', $people);
You will then need a route to access an individual person. The route will need to pass the persons ID into a controller method e.g.
Route::get('get-person/{id}',
[ 'as' => 'get-person',
'uses' => 'PeopleController#getPerson' ]);
You can then use this route in your view to get the links to each person
#foreach($people as $person)
{{$person->name}}
#endforeach
This would produce the list of links you want.

Laravel back using {{ URL::previous() }} doesn't work if there are validation errors

I want to make a cancel button on a simple CRUD edit form. However it seems that when there are validation errors the cancel button does not work.
I guess because it routes from controller#edit to controller#update the button just goes to controller#edit again instead of the actual previous page. Is this normal or did I do something wrong? How do I make it work?
attendee/edit.blade.php
<div class=pull-right>
{{Form::submit('Update',array('class'=>'btn btn-success'))}}
<a href = "{{URL::previous()}}" class = 'btn btn-warning'>Cancel</a>
</div>
{{ Form::close() }}
routes.php
Route::get('user/attendees', 'UserController#getAttendees');
Route::resource('attendee', 'AttendeeController');
attendee controller
public function edit($id)
{
$user = Auth::user();
if(empty($user->id))
return Redirect::to('/');
//return if attendee doesn't belong to user
if( !($user->attendee->contains($id)) )
return Redirect::to('user/index')->with( 'error', 'attendee id error.' );
$attendee = Attendee::find($id);
return View::make('attendees.edit', compact('attendee'));
}
/**
* Update the specified attendee in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$attendee = Attendee::findOrFail($id);
$validator = Validator::make($data = Input::all(), Attendee::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput()->with('id', $id);
}
$attendee->update($data);
return Redirect::intended();
}
user controller
public function getAttendees()
{
list($user,$redirect) = $this->user->checkAuthAndRedirect('user');
if($redirect){return $redirect;}
// Show the page
return View::make('site/user/attendees/index', compact('user'));
}
It's actually working correctly, it's just the usage that is incorrect.
Take the following:
You submit a form at GET /attendee/edit/{id}
The form takes you to POST /attendee/edit/{id}
You fail validation and are redirected to GET /attendee/edit/{id}
You cannot link to a page using a method other than GET. Your previous route was actually POST /attendee/edit/{id} but the link will always be GET.
Instead, nominate a page to be redirected to, I usually use the index for the section.
I think you should add a hidden input, like this
{!! Form::hidden('redirect_to', old('redirect_to', URL::previous())) !!}
and use this value in your link:
cancel
Redirect::back() doesn't really accomplish the right thing when using the validator provided by Laravel. What I've done before is pass the page to redirect back to as a hidden input in the form, and simply ignore it using Input::except("return"). Here's what I mean:
// On your HTML Form
<input type="hidden" name="return" value="{{ Request::path() }}" />
// In your PHP Controller
$validator = Validator::make($data = Input::except("return"), Attendee::$rules);
if ($validator->fails())
{
return Redirect::to(Input::get("return"))->withErrors($validator)->withInput()->with('id', $id);
}
Hope that can help shed some light. Other options are returning to a higher up, such as instead of attendee/edit/{id} redirect to attendee/edit/, but it all depends on the structure of you website.
I am now using the browser back via JS in onclick. Seems to work:
<a onclick="window.history.back();">Back</a>
I used this jquery for the cancel button.
$(document).ready(function(){
$('a.back').click(function(){
parent.history.back();
return false;
});
});
May you use the Front-End validation to test the input validation without a need to reload the page. So the {{URL::previous()}} won't affected.
The simple way to do that is by using Ajax or validator.js in your Laravel cade.
Here is a full example how to use jquery ajax in Laravel 5 to test the validation, may help:
http://itsolutionstuff.com/post/laravel-5-ajax-request-validation-exampleexample.html

Serialize Laravel Query Builder

I would like to be able to construct a query using laravel, and serialize it into a url string.
This would allow me to create routes which would unserialize a query builder, run the query, and make a view which displays the database results.
For example, to implement a button which refreshes a list of posts made by kryo:
http://example.com/ajax/posts.php?name=kryo&order_by=created_at&order_type=desc
Posts.php would simply be a route which unserializes, validates, and runs the query in the url params, and provides the results to a view.
Perhaps this is not useful in general, but I would personally find it handy specifically for ajax requests. If anyone knows how to implement this as a laravel plugin of some nature, that would be fantastic.
I'll try to give you a basic idea:
In Laravel you have to create a route to make a request to a function/method, so at first you need to create a route which will be listening for the ajax request, for example:
Route::get('/ajax/posts', array('uses' => 'PostController#index', 'as' => 'showPosts'));
Now, create a link in the view which points to this route, to create a link you may try this:
$url = to_route('showPosts');
If you use something like this:
<a class='ajaxPost' href="{{ $url }}?name=kryo&order_by=created_at&order_type=desc">Get Posts</a>
It'll create a ink to that route. So, make sure you are able to pass that $url to your JavaScript or manually you can write the url using /ajax/posts?name=.... Once you done creating the link then you need to create your JavaScript handler for this link (maybe using click event) then handle the click event from your handler, make ajax request, if it's jQuery then it could be something like this:
$('.ajaxPost').on('clcik', function(e){
e.preventDefault();
var url = $(this).attar('href');
$.getJSON(url, function(response){
$.each(response, function(key, value){
// loop... you may use $(this) or value
});
});
});
In your PostController controller class, create the index method:
class PostController extends BaseController {
public function index()
{
$name = Input::get('name');
$order_by = Input::get('order_by');
$created_at = Input::get('created_at');
$order_type = Input::get('order_type');
$posts = Post::whereName($name)->orderBy($order_by, $order_type)->get();
if(Request::ajax()) {
return Response::json($posts);
}
else {
// return a view for non ajax
}
}
}
If you want to send a rendered view from the server side to your JavaScript handler as HTML then change the getJson to get and instead of return Response::json($posts); use
return View::make('viewname')->with('posts', $posts);
In this case make sure that, your view doesn't extends the master layout. This may not be what you need but it gives you the idea how you can implement it.

Resources