How to get my link to display as a link from my laravel controller - laravel

I'm trying to send an error message with a link. The issue I'm having is that when I get the error I get the html version of my link
EG: Please go to product
What I would like is for my error message to say Please go to product where as product would be a link.
Here is my code
public function updateProduct(Product $product)
{
if(!empty($product->status))
{
$url = "Product";
return redirect()->route('product.index', [$product])->with('error', "Go to $url.");
}
}
and in my index.blade.php
I have this
#section('content')
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<table class="table">
#foreach($products as $product)
<tr>
<td>
{{ $product->name }}
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
#endsection
#push('js')
<script type="text/javascript">
#if(session('error'))
Swal.fire('Error!', '{{ session('error') }}', 'error');
#endif
</script>
#endpush

you are sending html as response. you have to use {!! !!} to print that response as your expectation.
#push('js')
<script type="text/javascript">
#if (session('error'))
Swal.fire('Error!', '{!! session('error') !!}', 'error');
#endif
</script>
#endpush
this will show the swal as Go to Product

Related

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

How to use pagination on ajax data

I want to use default pagination in laravel in view fetched by ajax function. put I get an error.
ajax function
public function get_products($id){
$products = Product::where('category_id',$id)->where('is_hidden','0')->paginate(9);
$category = Category::find($id);
$returnHTML = view('products_ajax')->with('products', $products)->with('category', $category)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
returned view by ajax
<h3>{{$category->name}}</h1>
<hr>
<div class="cards">
#foreach($products as $product)
<div class="card" data-item-id="{{$product->id}}">
<img style="width:50%;" src="{{asset('storages/images/products/'.$product->image)}}">
<div class="card-details">
<p class="card-brand">{{$product->brand->name}}</p>
<p class="card-name" title="Food Name Here Food Name Here Food Name Here Food Name Here">
{{$product->code}}
</p>
<p class="card-price" hidden> {{$product->price}}</p>
<p hidden class="card-full-des">
{{strip_tags(html_entity_decode($product->description))}}
</p>
<p class="card-packing">
<span>{{$product->packing}}</span>
</p>
{{-- <p class="card-packing">
<span>Packing: 12-8 oz (225g)</span>
</p> --}}
<div class="card-foot">
<button class="mbtn5" onclick="CardAddToCartOrDetails(this, true)">Add to Cart</button>
<button class="mbtn4" onclick="CardAddToCartOrDetails(this, false)">Details</button>
</div>
</div>
</div>
#endforeach
{{$products->links()}}
</div>
</div>
but I get this error:
so, can anyone help me?
The MethodNotAllowedHttpException is caused by a calling a route with a wrong method.
i.e. defining a GET route for /users and calling it with POST would result in this error.

Why output using ajax not display in table but json format?

I want to create a searching filters and display the output using ajax.
This is the button for submit the data:
{!! Form::open(['method' => 'POST', 'action' => 'Modul\CarianAnugerahController#search']) !!}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
This is the output table under the form:
<div class="panel panel-default">
<div class="panel-heading">Senarai Calon Anugerah</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if(Auth::check())
<div class="container table-responsive col-lg-12">
<!-- <div class="container text-center"> -->
<table class="table table-striped table-bordered" id="calon_table" >
<thead>
<tr>
<td class="text-center col-lg-3"><strong>Name</strong></td>
<td class="text-center"><strong>Action</strong></td>
<!-- <td class="text-center"><strong>Lihat Rekod</strong></td> -->
</tr>
</thead>
<tbody id="calon_anugerah">
</tbody>
</table>
<!-- </div> -->
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The ajax code to get the data is:
<script type="text/javascript">
$('#search').on('click', function(){
$.get("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
// alert(value.name);
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>
I had queried the data using the code in CarianAnugerahController#search:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('umur')) {
$query->whereRaw('YEAR(CURDATE()) - lahir_yy >= ?', [request('umur')]);
}
if(request('negeri_lahir')) {
$query->where('NegeriID', request('negeri_lahir'));
}
if(request('kategori')) {
$query->where('CategoryID', request('kategori'));
}
if(request('pangkat')) {
$query->where('OperasiID', request('pangkat'));
}
$newitem = $query->get();
return response($newitem);
This is the route:
Route::resource('carian_anugerah', 'Modul\CarianAnugerahController');
Route::post('/search-calon', 'Modul\CarianAnugerahController#search');
I can get the value but it doesn't display in table..it shows the output in json format in a white page..
example output..in browser.
What is missing in the ajax code?

Why the query from controller not display in table using ajax in Laravel?

I want to create a searching filters and display the output using ajax.
This is the button for submit the data:
{!! Form::open(['method' => 'POST', 'action' => 'Modul\CarianAnugerahController#search']) !!}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
This is the output table under the form:
<div class="panel panel-default">
<div class="panel-heading">Senarai Calon Anugerah</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if(Auth::check())
<div class="container table-responsive col-lg-12">
<!-- <div class="container text-center"> -->
<table class="table table-striped table-bordered" id="calon_table" >
<thead>
<tr>
<td class="text-center col-lg-3"><strong>Name</strong></td>
<td class="text-center"><strong>Action</strong></td>
<!-- <td class="text-center"><strong>Lihat Rekod</strong></td> -->
</tr>
</thead>
<tbody id="calon_anugerah">
</tbody>
</table>
<!-- </div> -->
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The ajax code to get the data is:
<script type="text/javascript">
$('#search').on('click', function(){
$.get("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>
I had queried the data using the code in CarianAnugerahController#search:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('umur')) {
$query->whereRaw('YEAR(CURDATE()) - lahir_yy >= ?', [request('umur')]);
}
if(request('negeri_lahir')) {
$query->where('NegeriID', request('negeri_lahir'));
}
if(request('kategori')) {
$query->where('CategoryID', request('kategori'));
}
if(request('pangkat')) {
$query->where('OperasiID', request('pangkat'));
}
$newitem = $query->get();
return response($newitem);
This is the route:
Route::resource('carian_anugerah', 'Modul\CarianAnugerahController');
Route::post('/search-calon', 'Modul\CarianAnugerahController#search');
I can get the value but it doesn't display in table..it shows the output in json format in a white page..
example output..in browser.
What is missing in the ajax code?
I guess you should remove form action and method. Because if you are submitting form via ajax you dont need action and method. Due to action and method your form is submitting like normal post of form data and that`s why you are receiving output on browser.
{!! Form::open() !!}
{{ csrf_field() }}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
Try these changes and see if you are getting desired result. And make ajax call with post, your search-calon route is POST
<script type="text/javascript">
$('#search').on('click', function(){
$.post("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>

Displaying feeds and blogs according to the created time

I'm having a home page where all the feeds along with comments and blogs are being displayed. Right now it is showing first all the feeds and then the blog. But I want it should be displayed according to the created time, mixer of feeds and blog not like first feed will come and then the blog. Can anyone tell me how to acheive that. This is my index.blade.php
#extends('layouts/default')
{{-- Page title --}}
#section('title')
Home
#parent
#stop
{{-- page level styles --}}
#section('header_styles')
<!--page level css starts-->
<link rel="stylesheet" type="text/css" href="{{ asset('assets/css/frontend/action.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('assets/css/frontend/tabbular.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('assets/css/frontend/jquery.circliful.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('assets/vendors/owl.carousel/css/owl.carousel.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('assets/vendors/owl.carousel/css/owl.theme.css') }}">
<!--end of page level css-->
#stop
{{-- content --}}
#section('content')
<div class="row">
<div class="column col-md-1 col-xs-1 col-sm-1"></div>
<div class="column col-md-3 col-xs-3 col-sm-3"><!--gm-editable-region--> </div>
<div class="column col-md-4 col-xs-4 col-sm-4">
#include ('action.partials.form')
#include ('action.partials.error')
#include ('action.partials.feed')
#include ('action.partials.blogfeed')
</div>
<div class="column col-md-3 col-xs-3 col-sm-3"><!--gm-editable-region--></div>
<div class="column col-md-1 col-xs-1 col-sm-1"></div>
#stop
{{-- footer scripts --}}
#section('footer_scripts')
<!-- page level js starts-->
<script type="text/javascript" src="{{ asset('assets/js/frontend/jquery.circliful.js') }}"></script>
<script type="text/javascript" src="{{ asset('assets/vendors/owl.carousel/js/owl.carousel.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('assets/js/frontend/carousel.js') }}"></script>
<script type="text/javascript" src="{{ asset('assets/js/frontend/index.js') }}"></script>
<!--page level js ends-->
#stop
This is action.partials.feed
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div><input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" /></div>
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($feed->comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
</div>
</article>
#endforeach
action.partials.blogfeed
#foreach($blogs as $blog)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="media-object" src="{{ URL::to('/uploads/users/'.$blog->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $blog->user->first_name }}
{{ $blog->user->last_name }}
<small> posted blog</small>
</strong>
{{ $blog->created_at->diffForHumans() }}<br><hr>
<h4>{{ $blog->title }}</h4>
<div class="featured-post-wide thumbnail">
#if($blog->image)
<img src="{{ URL::to('/uploads/blog/'.$blog->image) }}" class="img-responsive" alt="Image">
#endif
</div>
</div>
</article>
#endforeach
This is my feedcontroller
<?php
namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;
class FeedsController extends Controller
{
public function index() {
// $comments = Comment::latest()->get();
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index', compact('feeds', 'blogs'));
}
public function store(Requests\CreateFeedRequest $request)
{
$request->merge( [ 'user_id' => Sentinel::getuser()->id] );
Feed::create($request->all());
return redirect('home');
}
public function storecomment(Requests\CommentRequest $request, Feed $feed)
{
$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
return redirect('/home');
}
}
Can any one tell me how to display feeds and blogs according to the published time.
In your controller index method, try something like this:
public function index() {
// $feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
// $blogs = Blog::latest()->simplePaginate(5);
// $blogs->setPath('blog');
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->paginate(5);
$feeds = $feeds->merge($blogs)->sortByDesc('created_at');
return view('action.index', compact('feeds'));
}
The biggest problem you're going to have is that your Feed object is likely different than your Blog object. Meaning each will have unique column names that the other doesn't have. This is going to make doing the foreach a bit of a mess...
Remove #include ('action.partials.blogfeed'). This is not longer relevant for us.
In action.partials.feed...we'll output it all (hopefully without too many "hacks" and conditionals):
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>
{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
// We'll use #if(isset($feed->title)) to check if it's a blog post, aka ugly hack.
#if(isset($feed->title))
{{ $blog->created_at->diffForHumans() }}
<br><hr>
<h4>{{ $blog->title }}</h4>
<div class="featured-post-wide thumbnail">
#if($blog->image)
<img src="{{ URL::to('/uploads/blog/'.$blog->image) }}" class="img-responsive" alt="Image">
#endif
</div>
#else
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div><input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" /></div>
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($feed->comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
#endif
</div>
</article>
#endforeach
Because Illuminate\Database\Eloquent extends Illuminate\Support\Collection, we can easily merge them together. Because both $feeds and $blogs are an Eloquent Collection, we can easily merge them into one collection:
$feeds_and_blogs = collect($feeds->toArray(), $blogs->toArray());
Now you will have a combination of both. Because you've used $table->timestamps() in your migration to get your columns, we can easily perform a comparison against the created_at timestamp to get the sorting that you want:
$sorted_feeds_and_blogs = $feeds_and_blogs->sortBy(function($item){
return $item->created_at;
});
However, you likely want them to be sorted by newest first. Thankfully, collections have a sortByDesc function which will do exactly what we want.
Although in the grand scheme of things you probably really want a Polymorphic relationship.

Resources