So I have my car project and I want my cars to be Likeabel. So I installed overtrue likeable with composer require overtrue/laravel-follow, and do everything that is required. I followed tutorial from here.
So this is my code. My CarsController#ajaxRequest:
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function ajaxRequest(Request $request){
$car = Car::find($request->id);
$response = auth()->user()->toggleLike($car);
return response()->json(['success'=>$response]);
}
This is my route in web.php : Route::post('ajaxRequest', 'CarsController#ajaxRequest')->name('ajaxRequest');.
This is my cars index.blade.php:
#foreach($cars as $car)
#if($car->placeni_status != 0)
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" data-id="{{ $car->id }}">
<div class="auto-listing">
<div class="cs-media auto-media-slider">
#foreach (explode('|', $car->fotografije) as $fotografija)<?php $img = explode('|', $car->fotografije); ?>
<figure>
<img src="/slike_oglasa/{{$fotografija}}" alt="#"/>
<figcaption>
<span class="auto-featured">PREMIUM</span>
<i class="icon-play3"></i>
<div class="cs-photo">8 Photos</div>
</figcaption>
</figure>
#endforeach
</div>
<div class="auto-text">
<span class="cs-categories">Timlers Motors</span>
<div class="post-title">
<h4>{{$car->naslov}}</h4>
<h6>{{$car->naslov}}</h6>
<div class="auto-price"><span class="cs-color">{{$car->cijena}} €</span> <em>{{$car->vrsta_cijene}}</em></div>
<img src="assets/extra-images/post-list-img1.jpg" alt=""/>
</div>
<ul class="auto-info-detail">
<li>Godiste<span>{{$car->godiste}}</span></li>
<li>Kilometraza<span>{{$car->kilometraza}}</span></li>
<li>Mjenjac<span>{{$car->mjenjac}}</span></li>
<li>Gorivo<span>{{$car->gorivo}}</span></li>
</ul>
<div class="btn-list">
<div id="list-view" class="collapse">
<ul>
<li><b>Marka:</b> {{$car->marka}}</li>
<li><b>Model:</b> {{$car->model}}</li>
<li><b>Kubikaza:</b> {{$car->kubikaza}}cc</li>
<li><b>Kilovata:</b> {{$car->kilovata}}kW</li>
<li><b>Konjska snaga:</b> {{$car->konjska_snaga}}ks</li>
<li><b>Registrovan do:</b> {{$car->registracija}}</li>
</ul>
</div>
</div>
<div class="cs-checkbox">
<input type="checkbox" name="list" value="check-listn" id="check-list">
<label for="check-list">Uporedi</label>
</div>
<i id="like{{$car->id}}" class="glyphicon glyphicon-thumbs-up {{ auth()->user()->hasLiked($car) ? 'like-post' : '' }}"></i> <div id="like{{$car->id}}-bs3">{{ $car->likers()->get()->count() }}</div>
<label for="check-list1" style="text-transform: uppercase; color:gray;font-size: 11px;padding-left: 10px;"> {{$car->user->city}}</label>
Pogledajte vise<i class=" icon-arrow-long-right"></i>
</div>
</div>
</div>
#else
And this is script for like system:
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('i.glyphicon-thumbs-up, i.glyphicon-thumbs-down').click(function(){
var id = $(this).parents(".panel").data('id');
var c = $('#'+this.id+'-bs3').html();
var cObjId = this.id;
var cObj = $(this);
$.ajax({
type:'POST',
url:'/ajaxRequest',
data:{id:id},
success:function(data){
if(jQuery.isEmptyObject(data.success.attached)){
$('#'+cObjId+'-bs3').html(parseInt(c)-1);
$(cObj).removeClass("like-post");
}else{
$('#'+cObjId+'-bs3').html(parseInt(c)+1);
$(cObj).addClass("like-post");
}
}
});
});
$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
});
</script>
But when I press like and inspect it in console it shows me error:
jquery.js:4 POST http://localhost:8000/ajaxRequest 419 (unknown status)
and in preview it shows me this:
{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
message: "CSRF token mismatch."
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "C:\engineering\xampp\htdocs\autoplac\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"
line: 208
trace: [{,…},…]
You can add the route to App\Http\Middleware\VerifyCsrfToken ,$except array to disable csrf check for specific route.
Or you can submit your csrf token in your ajax request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
check the doc
Related
I am working on a search filter, fetching data from db through ajax call, text data is rendering but the image is not rendering, the link is also present in console image tag, but not showing in the blade view... if I submit it through form it renders data and images as well, please guide me... Thanks
Here's my blade code:
#if (count($product)>0)
#foreach ($product as $row)
<div class="col-sm-6 col-lg-4 px-2 mb-3">
<div class="card shadow-sm">
<div class="card-img position-relative">
<div class="owl-carousel position-relative">
#if (count($row->images)>0)
#foreach($row->images as $images)
<div> <img class="w-100" height="180px" width="250" src="{{ asset('carchain_private/public/src/uploads/ImagesP'.$row->product.'/'.'u_'. $row->user_id.'/'.'qr_'.$row->id.'/' . $images->name) }}"></div>
#endforeach
#else
<div> <img src="{{URL::asset('src/img-market/car.jpg')}}" alt="image"> </div>
#endif
</div>
<div
class="imgs-num rounded-pill bg-white light-color d-inline-flex align-items-center px-2">
<img class="camera-icon mr-1"
src="{{URL::asset('src/img-market/camera-to-take-photos.png')}}" alt="camera icon">
{{count($row->images ?? '0')}}
</div>
</div>
Here's my controller code:
$product = DB::table('manual_lovers')->select("*")
->leftJoin('users','manual_lovers.user_id','=','users.id')
->leftJoin('location_manual_collectors','manual_lovers.id','=','location_manual_collectors.user_id')
->leftJoin('prices_manual_collectors','manual_lovers.id','=','prices_manual_collectors.user_id')
->select('manual_lovers.*','users.user_type','prices_manual_collectors.price','prices_manual_collectors.currency','location_manual_collectors.address','location_manual_collectors.latitude','location_manual_collectors.longitude')
->get();
if($request->ajax()){
$page = view('marketplace.search_results_append', compact('product'))->render();
return response()->json(array(['page' => $page, 'count' => $count]));
}
here's the ajax call:
<script>
$('#condition,#price_min,#price_max,#year_min,#year_max,#mileage_from,#mileage_to,#location,#latitude,#longitude,#distance_km,#search_make,#model,#search_body,#country,#color,#sort_by').on('change',function(e){
e.preventDefault();
var condition = $('#condition').val();
var price_min = $('#price_min').val();
var price_max = $('#price_max').val();
var year_min = $('#year_min').val();
var year_max = $('#year_max').val();
var mileage_from = $('#mileage_from').val();
var mileage_to = $('#mileage_to').val();
var location = $('#location').val();
var latitude = $('#latitude').val();
var longitude = $('#longitude').val();
var distance_km = $('#distance_km').val();
var search_make = $('#search_make').val();
var model = $('#model').val();
var search_body = $('#search_body').val();
var country = $('#country').val();
var color = $('#color').val();
var sort_by = $('#sort_by').val();
$.ajax({
beforeSend: function(){
$('.ajax-loader').css("visibility", "visible");
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:"{{route('advanced_search')}}",
method:"POST",
dataType:"json",
data:{
condition:condition,
price_min:price_min,
price_max:price_max,
year_min:year_min,
year_max:year_max,
mileage_from:mileage_from,
mileage_to:mileage_to,
location:location,
latitude:latitude,
longitude:longitude,
distance_km:distance_km,
search_make:search_make,
model:model,
search_body:search_body,
country:country,
color:color,
sort_by:sort_by
},
success:function(data) {
// console.log(data);
$('#result_count').html(data[0].count);
$('#search_results_append').html(data[0].page);
},
complete: function(){
$('.ajax-loader').css("visibility", "hidden");
},
});
});
</script>
Here's the console's picture:
Here's the blade's view:
i want to add a function using laravel and vuejs and axios but it gives me error Error: "Request aborted".if I delete form validation system and checkForm function it all works well,really i don't know what error sign what,what kind of error.
fonction.blade.php
<section id="main-content">
<section class="wrapper">
<div class="container" id="app">
<div id="login-page">
<div class="form-login">
<div class="login-wrap">
<form #submit="checkForm">
<div v-if="errors.length">
<div class="alert alert-danger" role="alert">
<ul>
<li v-for="error in errors">#{{ error }}</li>
</ul>
</div>
</div>
<input type="text" class="form-control" id="fonction" name="fonction" v-model="fonction.fonction" placeholder="fonction">
<br>
<button class="btn btn-theme" #click="addFonction">AJOUTER FONCTION</button>
</form>
</div>
</div>
</div>
</div>
</section>
</section>
<script src="{{asset('js/vue.js')}}"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
vuejs
<script>
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
'url' => url('/')
]) !!};
</script>
<script>
var app = new Vue({
el: '#app',
data: {
errors: [],
fonctions:[],
fonction:{
fonction :''
}
},
methods:{
checkForm: function (e) {
if (this.fonction.fonction) {
return true;
}
this.errors = [];
if (!this.fonction.fonction) {
this.errors.push('fonction required.');
}
e.preventDefault();
},
addFonction:function(){
axios.post(window.Laravel.url+'/addfonction/', this.fonction)
.then(response => {
//console.log(response.data);
this.fonctions.unshift(this.fonction);
this.fonction={
fonction:''
}
})
.catch(error=>{
console.log(error);
})
},
},
});
</script>
SalarieController.php
public function addFonction(request $request){
$fonction = new Fonction;
$fonction->fonction = $request->fonction;
$fonction->save();
Response()->json(['etat' => true]);
}
Same question, maybe it connect with <form> tag.
I am solve for myself by replace <form> this tag with <div> tag. Also I replace all submit events with click ones on button.
I got some error when im updating the div content in my laravel project. I use the setInterval method. But when i put my route in the load parameter it throws me an error. Can someone know why Im getting this error?
shownews.blade.php
<h4 class="comments-title" > <span class="fas fa-comment-alt"></span>
{{$news->comments()->count()}}
Comments</h4>
<div class="row" >
<div class="col-md-12 col-md-offset-2" style="overflow-y: scroll; height: 400px;
width: 400px; " id="commentarea" >
#foreach($news->comments as $comment)
<div class="comment" style="background-color: #f6efef;" >
<div class="author-info">
<img src={{"https://www.gravatar.com/avatar/" . md5(strtolower(trim($comment->email))) . "?s=50&d=retro" }} class="author-image" id="image">
<div class="author-name">
<h4>{{$comment->name}} </h4>
<p class="author-time"> {{ date('jS F, Y - g:iA' ,strtotime($comment->created_at)) }}</p>
</div>
</div>
<div class="comment-content">
{{$comment->comment}}
</div>
</div>
#endforeach
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function() {
$('#commentarea').load('{{ action('NewsController#showNews') }}');
}, 1000);
});
</script>
web.php
Route::group(['middleware'=>['web']], function(){
Route::get('/article/{id}', 'NewsController#showNews')->name('article');
});
//comments
Route::post('comments/{news_id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
Error Message:
Missing required parameters for [Route: article] [URI: article/{id}]. (View: D:\coindeoro_admin\adminPanel\resources\views\coin\shownews.blade.php)
The error is pretty clear no ? Your controller function is expecting an $news_id parameter to work.
Just pass the news ID in your route :
$('#commentarea').load('{{ action('NewsController#showNews', ['news_id' => $news->id]) }}');
im new to laravel and i dont know how to do this.
i want to insert this #{{comment.user.avatar}}
inside this <img src={{ asset("images/profile/{comment.user.avatar}") }} />
what im getting is this
<img src="http://localhost:89/images/profile/{comment.user.avatar}">
what i want is
<img src="http://localhost:89/images/profile/avatarpicture.jpg">
this is my complete code
<div class="card" v-for="comment in comments">
<div class="card-content">
<div class="media">
<div class="media-left">
<img src={{ asset("images/profile/") }}#{{comment.user.avatar}} style='height:50px; width:50px' />
</div>
<div class="media-content">
<p class="subtitle is-6">#{{comment.user.firstname}} said...</p>
<p>
#{{comment.body}}
</p>
<span style="color: #aaa;" class="is-size-7">on #{{comment.created_at}}</span>
</div>
</div>
</div>
</div>
and this is my javascript
#section('scripts')
<script>
const app = new Vue({
el: '#app',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
},
mounted(){
this.getComments();
// this.listen();
},
methods:{
getComments(){
axios.get(`/api/posts/${this.post.id}/comments`)
.then((response) => {
this.comments = response.data
})
.catch(function(error){
console.log(error);
})
},
}
});
</script>
thank you in advance
arnel
Vue interpolation cannot be used inside HTML attributes. You must bind an expression and wrap it in quotes. Note :src is short hand for v-bind:src.
<img :src="'{{ asset("images/profile/") }}' + comment.user.avatar">
By doing this, you're binding the concatenated string:
'http://localhost:89/images/profile/' + comment.user.avatar
Hello i'm a new developer and in my laravel project i have implemented a real time group chat that uses ajax but now i need a real time chat between users in ajax i have tried many things but none have worken it would be very helpful if you could help me or if could send me a link to a good tutorial
Here's the index of my group chat :
#extends('admin.app')
#section('content')
<div class="container">
<div class="row" style ="padding-top:40px;">
<h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
<br/><br/>
<div class="col-md-2">
<p>Users online</p>
#foreach($users as $user)
#if($user->isOnline())
<li>{{$user->FullName}}</li>
#endif
#endforeach
</div>
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
Recent Chat
</div>
<div class="panel-body">
<ul class="media-list" id="message">
#foreach($messages as $message )
<li class="media">
<div class="media-body">
<div class="media">
<div class="media-body" >
{{$message->message}}
<br/>
<bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
</small></bold>
<hr>
</div>
</div>
</div>
</li>
#endforeach
</ul>
<div>
<div class="panel-footer">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Enter Message"/>
{{csrf_field()}}
<input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
<span class="input-group-btn">
<button type="submit" id="send" class="btn btn-info">Send</button>
</span>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(realTime, 2000);
});
function realTime() {
$.ajax({
type:'post',
url:'/chat/get',
data:{
'_token':$('input[name=_token]').val(),
},
success: function (data) {
$('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
for (var i=0; i < data.length; i++){
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
}
},
});
setTimeout(realTime, 2000);
}
$(document).on('click','#send', function (){
$.ajax({
type:'post',
url:'/chat/send',
data:{
'_token':$('input[name=_token]').val(),
'from_name':$('input[name=from_name]').val(),
'message':$('input[name=message]').val(),
},
success: function (data) {
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
}
})
$('input[name=message]').val('');
});
</script>
#stop
here are the routes of my group chat:
Route::get('/chat', 'Chat\ChatController#index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController#sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController#getMessage' );
here's my controllers of the group chat:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users=user::all();
$messages=message::all();
return view('admin.chat.index',['messages'=> $messages],compact('users'));
}
public function sendMessage(Request $request){
$send = new Message();
$send ->from_name = $request->from_name;
$send ->message = $request->message;
$send->save();
return response()->json($send);
}
public function getMessage(){
$message = Message::all();
return response()->json($message);
}
here the migration for my gruop chat :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->string('from_name');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
Sorry in advance for the bad english and it would very grateful if you could help me or if you could send the link of a good tutorial
You need a live connection for that using a websocket, and you can achieve this with Laravel.
What this does is actually keep the connection between the server and the clients open and allows the server to send data to the clients, not just the other way around. Therefore you are able to send the messages to one of the people in your chat as soon as you receive them from the other participant.
That's called Broadcasting in Laravel, take a look at the documentation here:
https://laravel.com/docs/5.5/broadcasting