Passing multiple variable with axios to controller laravel - php

I'm trying to insert a lecture id a students table. I need to pass the student's id as well as the lecture's to the controller. I'm using axios to post 2 parameters to the controller. My codes not working, did i do it wrong? New in Laravel. thanks
Vue Component
<i class="fas fa-user-plus"></i>
<script>
export default {
data () {
return {
student:'',
lecture_id:this.$route.params.id,
}
},
methods:{
setLectureFK($student_id){
axios.post('/api/internship/setLecture/'+$lecture_id,'/'+$student_id);
}
},
}
Controller
public function setLecture($lecture,$student)
{
$student = student::findOrFail($student);
$student->lecture_id_FK = $lecture;
$student->save();
}
API.PHP
Route::post('internship/setLecture/{lecture}/{student}', 'API\InternshipController#setLecture')->name('internship.setLecture');

As far as I can see there is the syntax error in your vue component .
In this line
axios.post('/api/internship/setLecture/'+$lecture_id,'/'+$student_id);
You have put the comma instead of + it should be like this
axios.post('/api/internship/setLecture/'+$lecture_id+'/'+$student_id);

Try this:
Vue Component
<i class="fas fa-user-plus"></i>
<script>
export default {
data () {
return {
student:'',
lecture_id:this.$route.params.id,
}
},
methods:{
setLectureFK(student_id){
axios.post('/api/internship/setLecture',{student_id:student_id,lecture_id:this.lecture_id});
}
},
}
Controller
public function setLecture(Request $request)
{
$student = student::findOrFail($request->student_id);
$student->lecture_id_FK = $request->lecture_id;
$student->save();
}
api.php
Route::post('internship/setLecture', 'API\InternshipController#setLecture')->name('internship.setLecture');

Related

search filter is not fetching data until clicking on search button

It's a laravel vuejs project. Here is the photo of my product page :
Products were supposed to display at that page, but it's completely null until I am clicking on the search button . After clicking on the search button, the page loads the products and the search option working as well.
My codes are :
web.php ->
Route::get('/', 'App\Http\Controllers\Mastercontroller#index');
Route::get('/search', 'App\Http\Controllers\Mastercontroller#search');
Route::any('{slug}', 'App\Http\Controllers\Mastercontroller#index');
Mastercontroller.php ->
<?php
namespace App\Http\Controllers;
use App\Models\myproductcase;
use Illuminate\Http\Request;
class Mastercontroller extends Controller
{
public function index(){
return view('welcome');
}
public function search(Request $r){
$search = $r->get('q');
return myproductcase::where('name','LIKE','%'.$search.'%')->get();
}
}
productpage ->
<template>
<div>
<div class="search"><input v-model="search" type=text></input><button
#click.prevent="makesearch()">Search</button></div>
<div class="product-list">
<div v-if="showsearch==true">
<div v-for="getresult in getdata" v-bind:key="getresult.id">
<div class="product">
<h1>{{getresult.name}}</h1>
<h3>{{getresult.price}}</h3>
<p>{{getresult.description}}</p>
</div>
</div>
<div v-if="showsearch==false">
no data found
</div>
</div>
</div>
</div>
</template>
<script>
export default{
data(){
return{
search : '',
showsearch : false,
getdata : []
}
},
methods : {
async makesearch(){
fetch('/search?q='+this.search).then(hi=>hi.json()).then(hi=>{
console.log();
this.getdata = hi;
this.search = '';
this.showsearch = true;
}).catch(err=>{
console.log(err);
});
}
},
}
</script>
The problem is when you load the page for the first time, there is not get query parameter in your url, so in the line
$search = $r->get('q'); // Is equal to NULL
The query that you are doing the first time is:
return myproductcase::where('name','LIKE','%NULL%')->get();
You could use the syntax below for setting up a default parameter
$search = $r->get('q', 'default value' );
PD: Be careful with SQL Injection Read this
Edit:
Also in your Component call in your mounted method the makesearch method.
data(){
...
}
...
mounted(){
this.makesearch()
}

Display list Vue Axios with Laravel

I'm new to laravel, axios and vue and I used this tutorial to help make a ToDo list:
I want to tweak the basic tutorial by allowing different users to store and view their tasks. I added new user registration and login, but each user would see everyone's list, not only theirs. So I made a one to many relationship between the User and Task model and added these methods to the models:
class User extends Authenticatable
{
...
public function tasks()
{
return $this->hasMany('App\Task');
}
}
class Task extends Model
{
...
public function user()
{
return $this->belongsTo('App\User');
}
}
I updated TaskController.php and TaskList.vue to display only the active user's tasks, but now in the view no list appears and new tasks can't be added.
Here is the code for the two. Everything is the same as the tutorial, except I commented next to the parts that I added:
<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
class TaskController extends Controller
{
$user = Auth::user(); //Added by me
public function index()
{
return Task::latest()->where('user_id', $user->id)->get(); //Added by me,
//this query returns whats expected in php artisan tinker
//was previously return Task::latest()->get();
//I also tried this: return $this->user->tasks->toJSON()
}
public function store(Request $request)
{
$this->validate($request, [
'body' => 'required|max:500'
]);
return Task::create([
'body' => request('body'),
'user_id' => $user->id //Added by me
]);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
$task->delete();
return 204;
}
}
In TaskList.vue
<template>
<div class='row'>
<h1>My Tasks</h1>
<h4>New Task</h4>
<form action="#" #submit.prevent="createTask()">
<div class="input-group">
<input v-model="task.body" type="text" name="body" class="form-control" autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">New Task</button>
</span>
</div>
</form>
<h4>All Tasks</h4>
<ul class="list-group">
<li v-if='list.length === 0'>There are no tasks yet!</li>
<li class="list-group-item" v-for="(task, index) in list">
{{ task.body }}
<button #click="deleteTask(task.id)" class="btn btn-danger btn-xs pull-right">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
task: {
id: '',
body: '',
user_id: '' ///Added by me
}
};
},
created() {
this.fetchTaskList();
},
methods: {
fetchTaskList() {
axios.get('api/tasks').then((res) => {
this.list = res.data;
});
},
createTask() {
axios.post('api/tasks', this.task)
.then((res) => {
this.task.body = '';
this.task.user_id = ''; ///added by me
this.edit = false;
this.fetchTaskList();
})
.catch((err) => console.error(err));
},
deleteTask(id) {
axios.delete('api/tasks/' + id)
.then((res) => {
this.fetchTaskList()
})
.catch((err) => console.error(err));
},
}
}
</script>
</script>
The app worked until I added the few lines mentioned above. Now nothing shows in the display and no new tasks can be added. I am new to laravel and totally new to axios and vue, but to me it seems like what I added should work. There are no error messages when I run it, it just doesn't produce what I want.

Laravel - Pagination doesn't work well

I have a view with a table and pagination for this table but when i use de pagination the view is duplicated.
my controller function:
public function index()
{
$items = Items::where('active', '=', 1)->paginate(5);
if (Request::ajax())
{
return View::make('app/items.index')->with('items', $items)->render();
}
else
{
return view('app/items.index', array('items' => $items));
}
}
my jquery:
function pagination()
{
$(document).on("click", ".pagination a", function(e)
{
e.preventDefault();
alert($(this).attr('href'));
$.ajax({
url: $(this).attr('href'),
})
.done(function(data)
{
console.log(data);
$('#listSearchItems').html(data);
});
});
}
my view:
#section('content')
<div class="header"></div>
<div id="listSearchItem" class="content">
<table>
</table>
#if($items->render())
<nav class="pagination">
<a href="{{$items->previousPageUrl()}}">
<i class="material-icons">arrow_back</i>
</a>
<a href="{{$items->nextPageUrl() }}">
<i class="material-icons">arrow_forward</i>
</a>
</nav>
#endif</div>#stop
And when i click at pagination button, the view code is all duplicated within the , the table information is updated but also adds all existing html of view, duplicating code.
Anyone can help me? I already search a lot about this problem, i don't know if is the how to return the information in the controller.
Thank's
there have some problems with your code.
first why you need ajax to render your datas?
if you need use ajax render datas, your controller should be like this:
public function index()
{
$items = Items::where('active', '=', 1)->paginate(5);
if (Request::ajax())
{
$datas = $items->items();
$results = '';
foreach ($datas as $item) {
$results .="<tr><td>{$item->whateverInYourTable}</td><td>{$item->whateverInYourTable}</td></tr>"
}
return $results;
}
else
{
return view('app/items.index', array('items' => $items));
}
}
if you don't need ajax controller should be like this:
public function index()
{
$items = Items::where('active', '=', 1)->paginate(5);
return view('app.items.index', array('items' => $items));
}
view like this:
<nav class="pagination">
{!! $items->render() !!}
</nav>

Post Data not working correctly Laravel

I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.
Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});
If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});

Laravel 5: Call to a member function sum() on null and other persistence issues

I have a threaded-comments list each with an upvote/downvote button using jquery.upvote.js.
The voting action is done through ajax and it works, making an upvote or a downvote gets registered in the database with the correct values. Removing the vote will delete the record from the database. So technically it works as intended.
However, I have 2 problems:
The votes that the user has made do not persist after page reload which is important otherwise users won't know what they voted on.
When I add this chunk of code {{ $each_comment->commentvotes->sum('value') }} to the view to grab the sum of the votes on a given comment, I get the following error:
Call to a member function sum() on null
Routes
Route::resource('votes', 'VotesController');
Route::resource('commentvotes', 'CommentVotesController');
I'd like to point out that I've used the same method successfully on posts' votes with Vote model and VoteController.
CommentVote model
class CommentVote extends Model
{
protected $table = 'commentvotes';
protected $fillable = [
'value',
'comment_id',
'user_id'
];
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->belongsTo('App\Comment');
}
}
CommentVotesController
class CommentVotesController extends Controller
{
public function __construct() {
$this->middleware('auth', ['only' => ['create', 'edit'] ]);
}
public function store(Requests\CommentVoteRequest $request)
{
$commentId = $request->input('commentId');
$userId = $request->user()->id;
$value = $request->input('value');
// Check to see if there is an existing vote
$vote = CommentVote::whereCommentId($commentId)->whereUserId($userId)->first();
if (!$vote)
{
// First time the user is voting
CommentVote::create(['comment_id' => $commentId, 'user_id' => $userId, 'value' => $value]);
} else {
$vote->value == $value ? $vote->delete() : $vote->update(['value' => $value]);
}
// AJAX JSON RESPONSE
return response()->json(['status' => 'success',
'msg' => 'Vote has been added.']);
}
}
Javascript
$(document).ready(function() {
$('.topic').upvote();
$('.comment').upvote();
$('.vote').on('click', function (e) {
e.preventDefault();
var $button = $(this);
var postId = $button.data('post-id');
var value = $button.data('value');
$.post('http://localhost/r2/public/votes', {postId:postId, value:value}, function(data) {
if (data.status == 'success')
{
// Do something if you want..
}
}, 'json');
});
$('.commentvote').on('click', function (e) {
e.preventDefault();
var $button = $(this);
var commentId = $button.data('comment-id');
var value = $button.data('value');
$.post('http://localhost/r2/public/commentvotes', {commentId:commentId, value:value}, function(data) {
if (data.status == 'success')
{
// Do something if you want..
}
}, 'json');
});
});
Relevant part of the view comment_list.blade.php
#foreach($comments as $each_comment)
<div class="col-md-1">
<div class="upvote comment" data-comment="{{ $each_comment->id }}">
<a class="upvote commentvote {{ $each_comment->commentvotes && $each_comment->commentvotes->contains('user_id', Auth::id()) ? ($each_comment->commentvotes->where('user_id', Auth::id())->first()->value > 0 ? 'upvote-on' : null) : null}}" data-value="1" data-comment-id="{{ $each_comment->id }}"></a>
<!-- Notice how we set the sum of the votes for this post here -->
<span class="count">{{ $each_comment->votes->sum('value') }}</span>
<a class="downvote commentvote {{ $each_comment->commentvotes && $each_comment->commentvotes->contains('user_id', Auth::id()) ? ($each_comment->commentvotes->where('user_id', Auth::id())->first()->value < 0 ? 'downvote-on' : null) : null}}" data-value="-1" data-comment-id="{{ $each_comment->id }}"></a>
</div>
</div>
#endforeach
You have to define the relation inside the Comments model. Otherwise the CommentVotes will not be accessible to Comment entities.

Categories