Laravel replace/convert #foreach loop to vue v-for loop with database relationship - laravel

Im making a laravel SPA and I recently learned how to use vue and I know how v-for works for vue using my components. I only know how to loop only in a single table without relation thats why I'm having a difficult time changing it. I have two tables which are news and comments, and this table news hasMany comments in it.
my blade file for now.
#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

your component goes like this in vue2.0
**block.vue**
<template>
<div class="comment" style="background-color: #f6efef;" v-for="comment in
news.comments" >
<div class="author-info">
<img :src="comment.author_image" }} class="author-image" id="image">
<div class="author-name">
<h4>{{ comment.name }} </h4>
<p class="author-time"> {{ comment.time }}</p>
</div>
</div>
<div class="comment-content">
{{ comment.comment }}
</div>
</div>
</template>
<script>
export default {
name: "block",
props: [ "news" ], //or
data() => ({ news: [] })
}
</script>

Related

Laravel Pagination not working in Blade file with Tailwind CSS

I'm trying to use Laravel pagination. The issue is that when I use the links() method in the Blade file, it gives an error. For example, when I use the URL "http://127.0.0.1:8000/tournaments?page=3," it works fine, but it gives an error in the Blade file, as explained below.
Controller
public function index()
{
return view('front.tournaments', [
'seriesdata' => $this->tournamentList()
]);
}
public function tournamentList()
{
return Series::leftJoin('team_squads as ts', 'ts.id_series', 'series.id')
->leftJoin('series_team_squads as sts', 'sts.id_series', 'series.id')
->leftJoin('admins as a', 'a.adminable_id', 'series.id')
->where('series.lang', 'en')
->orderBy('series.id', 'asc')
->groupBy('series.id')
->select('series.*')
->paginate(10)
->append([
'logo_url',
'location'
]);
}
Blade
#foreach($seriesdata as $series)
<div class="flex flex-inline xs:flex-col sm:flex-row">
<div class="w-full border-b">
<div class="flex justify-center items-start">
<div class="py-2 mx-auto sm:bg-white xs:bg-white w-full">
<a href="{{ url('tournaments/').'/'.$series->url.'/'.$series->id }}" class="flex">
<div class="grid grid-rows-1 grid-flow-col gap-1">
<div class="row-span-1 col-span-2">
<img src="{{ $series->logo_url }}" alt="avatar" class="object-cover w-12 h-12 mx-4">
</div>
<div class="row-span-1 col-span-2">
<h1 class="font-bold text-lg">{{ $series->name }}</h1>
<p class="uppercase font-light text-sm text-grey">{{ $series->location->address }}</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
#endforeach
{{ $seriesdata->links() }}
Error
It looks like your append() method is blocking pagination in blade. Try to remove it from tournamentList() in controller.
When you do ->append() after the ->paginate(), you are transforming what ->paginate() returns (basically a LenghtAwarePaginator) into a Collection, and Collection does not have a ->links() method. You can see this as the error shows you are trying to call links method in Illuminate\Database\Eloquent\Collection, that is how I know what ->append() is returning.

The POST method is not supported for this route. Supported methods: GET, HEAD."

How to pass the route in ajax in laravel without form?
I have a link or route without form.
<div class="row" id="markets">
#foreach($markets as $market)
<div class="col-lg-3">
<div class="card">
<img src="{{ asset('images/markets/'.$market->image) }}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ $market->title }}</h5>
<p class="card-text">{{ Str::words($market->body, 10) }}</p>
<p class="card-text">{{ $market->price }} $</p>
Add to cart
Continue
</div>
</div>
</div>
#endforeach
</div>
I want to do it with ajax.
<a role="button" class="card-text add-to-cart">Add to cart</a>
<script>
$(document).ready(function(){
$('.add-to-cart').on('click', function(event){
event.preventDefault();
var Route = $(this).attr('href');
$.ajax({
url: '{{ route("cart", $market->id) }}',
});
});
});
</script>
I see this error
My goal is to make this page.
try changing in web.php
Route::get('/cart/{market}',"MarketController#cart")->name('cart');
to
Route::match(['get', 'post'],'/cart/{market}',"MarketController#cart")->name('cart');
it seems you are using both get and post on same route if so then this may be it
EDIT:
try this
$('#markets').load('{{ route('cart') }} #markets')
What the above function does is it will load the cart route's market id and will replace the current route markets id
also i think it will be better to add
<div id="markets">
<div class="row">
#foreach($markets as $market)
<div class="col-lg-3">
<div class="card">
<img src="{{ asset('images/markets/'.$market->image) }}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ $market->title }}</h5>
<p class="card-text">{{ Str::words($market->body, 10) }}</p>
<p class="card-text">{{ $market->price }} $</p>
Add to cart
Continue
</div>
</div>
</div>
#endforeach
</div>
</div>
ie to create a div outside of the one you want to replace so the classes wont get mixed as for the for loop it will be only server sided so what you will load is loaded for-looped data

making pagination in laravel for image

Hello for everyone I have a problem in laravel that about the showing images in one view, the problem is: I have a page that just show the images but it show all the images stored in table with specific id but I want to show some of that and have a button (show more) and when click on button it show the other images I don't know hove can I do this if someone can help me please!
This is my controller code:
public function listHostel()
{
$hostels = Hostel::all();
return view('front/khabgah_list',compact('hostels'));
}
And this is my blade code:
#foreach($hostels as $hostel)
#foreach($hostel->attachments as $photo)
<div class=" col-12 col-sm-6 col-md-6 col-lg-3 px-1 mt-3">
<div class="card card-shadow custom-height-1 " style="border-radius: 0%">
<a href="">
<img src="/assets-/app/media/img/blog/hostels-img/{{$photo->file_name}}"
class="card-img-top card-img custom-card-img-height" alt="">
</a>
<div class="car-body">
<div class="card-footer">
<div class="custom-circle">
<p class="custom-circle-text card-text">
<b>
#if($hostel->type == 1)
{{ 'ذکور'}}
#else
{{ 'اناث' }}
#endif
</b>
</p>
</div>
<div class="custom-prices card-text text-left"> کرایه فی ماه
: {{$hostel->remark }}
</div>
</div>
</div>
</div>
</div>
#endforeach
#endforeach
Pagination is likely what you're looking for. Change your controller to:
public function listHostel()
{
$hostels = Hostel::all()->paginate(5);
return view('front/khabgah_list',compact('hostels'));
}
Then you can get the links in your Blade template:
{{ $hostels->links() }}
You might need to change it a bit to work for your specific situation. The documentation gives some more info: https://laravel.com/docs/5.8/pagination

Laravel allow links on message

I need allow links in messages, when user send message. How I can do this?
#foreach($mess as $message)
<li data-mid="{{ $message->id }}">
<div class="row margin-left-none margin-right-none">
<div class="col-md-2 padding-right-none">
<div class="avatar-user text-center">
<img src="{{ $message->sender->avatar }}" alt="$message->sender->name">
</div>
</div>
<div class="col-md-10 padding-left-none">
<div class="user-name">
<span>{{ $message->sender->name }}
#if(Helper::getOnlineUser($message->sender->id))
<i data-toggle="tooltip" title="Онлайн" class="material-icons online">fiber_manual_record</i>
#else
<i data-toggle="tooltip" title="Оффлайн" class="material-icons offline">fiber_manual_record</i>
#endif
<span class="date float-right">{{ $message->created_at->formatLocalized('%H:%m') }}</span></span>
</div>
<div class="message">
{{ $message->body }}
</div>
</div>
</div>
</li>
#endforeach
This is view of messages.
How I can allow links?
Example: http://example.com in messages =>
http://example.com
I need {!! $message->body !!} ? Or How?
In controller:
$mess = Chat::conversations($conversation)->for($user)->getMessages($limit, $request->page);
I use this package: https://github.com/musonza/chat
There are built in PHP functions to handle this:
<div class="message">
{!! strip_tags($message->body, '<a>') !!}
</div>
Where the second argument is your whitelist.
This has the following advantages:
You're not messing with regex
You're still using blade {!!!!}
You're using well tested code dev'ed by the core team
You can do it by using following php function in your blade,
<?php
function getDataWithURL($text){
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "".$url[0]." ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
}
?>
You just need to add this code in your blade file and then you can check and replace the links in your text like this,
<div class="message">
<?php getDataWithURL($message->body);?>
</div>
I hope you will understand.

Show a collection in laravel from controller on different columns in view

got this problem:
I want to show the info from a collection where a publication has a "featured" column in true.
$pub_destacadas = Publicaciones::take(3)->where('destacado', '=', 1)->get();
The problem is that my layout has 3 elements to fill with this information that have different sizes so i wasn't able to solve this using the chunk() method in the foreach in my blade template, so I tried the following:
$individual_destacada = $pub_destacadas->take(1);
$grupo_destacada = $pub_destacadas->take(2);
and show them in the view as follows:
<div class="publicaciones-destacadas">
<div class="container">
<h2>Publicaciones Destacadas</h2>
<div class="row">
#foreach($individual_destacada as $destacada)
<div class="col-md-6">
<div class="item-destacado size-2">
<img class="img-responsive" src="{{ asset('img/publicaciones/' . $destacada->imagen ) }}">
{{ $destacada->titulo }}
{{ $destacada->descripcion }}
</div>
</div>
#endforeach
<div class="col-md-6">
#foreach($grupo_destacada as $destacada)
<div class="row doble-publicacion">
<div class="col-md-12">
<div class="item-destacado size-1">
<img class="img-responsive" src="{{ asset('img/publicaciones/' . $destacada->imagen ) }}">
{{ $destacada->titulo }}
{{ $destacada->descripcion }}
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
So... now it shows it correctly in the layout but the first item that the query gets is shown 2 times in this layout. How can I exclude this first element in the second variable where I get the featured publications?
Hope I explained the problem correctly.
Here's the layout:
You can use splice.
$individual_destacada = $pub_destacadas->splice(1);
$grupo_destacada = $pub_destacadas->splice(2);

Resources