Laravel: Render queried Data whith Blade functions - laravel

Currently I'm getting some data from the database and after that I want to render it within my Blade template.
In my queried data I have blade functions like url('/foo') combined with some html. And here is the problem.
When I'm using {!! $child->description !!} the HTML is rendered correctly, but my Blade function won't work:
Function: url('/foo)
Output: http://myurl.de/url('/foo')
When I'm using the "normal" Syntax like {{ $child->description }} the generated URL is correct (http://myurl.de/foo), but the HTML is not rendered.
So my question is:
How can I use my queried Blade function within rendered HTML? ^^
/Edit
Okay, perhaps my question is too abstract. So I want to show you my problem based on my example. (generated template image - only on german, sorry)
Every form is a database entry like:
categoryName
categoryParent
...
categoryDescription
As you can see on my image, the categoryDescription is the small text under my first input field with the small button.
I want to use this script abstract as possible so that I can fill the entry with every content I want to fill in.
In this case my content is:
lore ipsum <a class="btn btn-primary btn-sm pull-right" href="url('foo')">dolor</a>
As you can see there is the mentioned Blade-function (url) and the HTML.

{!! !!} - this dont escapse string so if u have something from database like,
something it would output it like that.
While in other hand {{ }} this would give you just "something" without , it is used to protect you from injections.

Maybe blade error.{{}}
lore ipsum <a class="btn btn-primary btn-sm pull-right" href="{{url('foo')}}">dolor</a>
Laravel Blade

Related

Vue.js -- How do you display image using a URL in an array of an object within an array?

Good afternoon!
I am working on a project that has displaying images of the national parks. I have called the National Parks api and get back an array of all the national parks in the database. But I am trying to display the image using the URL provided that is currently embedded in the object in an array of objects marked 'images'.
images-array
This is my code in Vue.js:
<template>
<ul class="list">
<li v-for="park in parks" :key="park.parkCode" >
<img :src="park.images[0].url"/>
<h4>{{park.name}}</h4>
</li>
</ul>
</template>
But every time I run it, I get this error...
Error in render: "TypeError: Cannot read property 'url' of undefined"
I know it is probably something stupid simple, but my brain can't seem to figure it out.
Thank you in advance!
You should check the response.
If park object includes images like
{ ..., "images" : ['image.png','image2.png], ...}
you should try park.images[0]
if it looks like
{ ..., "images" : [{'url':'image.png'},{'url':'image2.png'}], ...}
it should be ok.

Blade view for rich text field on description tag

I'm using voyager in a laravel 7 shopping app for the description of all products.
I want to output the field for the description of the product
#section('description', {!! $item->description !!} )
and
for the facebook share = og:description" content="{!! $item->description !!}">
When I use {!! $item->description !!} in the body, no problem. But in the tag the output always read the p tag and all style form the description.
The weird thing is it's working find on localhost but not on the server. I tried various combination of solution with the same result. I feel there's a quick or maybe it's just not possible?
try html_entity_decode() ref link https://www.php.net/manual/en/function.html-entity-decode.php
{!! $item->description !!}
to
{!! html_entity_decode($item->description) !!} // it will render html
If you are using laravel 7/8 you can create a blade component then you can simple call
<x-editor :content="$description></x-editor>
check out this laravel docs
try this:
{{strip_tags(trim($item->description)}}

Laravel pagination with URL parameter

I have a Laravel application. One of the pages can be reached via the following URL
http://localhost:8000/items/gallery?item_type=glasses
As the amount of items to be shown can be quite substantial, I'm using pagination. I have the following code in my view:
#foreach($media as $media_item)
<div class="col-md-3">
<div class="card">
<img class="card-img-top" src="{{ asset('storage/'.$media_item->id .'/'. $media_item->file_name) }}" ">
</div>
</div>
#endforeach
{{ $media->links() }}
and in the controller, I'm using:
$media = Media::paginate(5);
The pagination buttons are shown and work for the 1st one. Then when I click on the second (or third or fourth...) one, I get the following error message:
Method Illuminate\Database\Eloquent\Collection::links does not exist.
I see the link is trying to reach:
http://localhost:8000/beeritems/gallery?page=2
whereas I need:
http://localhost:8000/beeritems/gallery?item_type=glasses&page=2
In Laravel, how can I change the links() method to include the part after the question mark?
You must use ->appends() methods
$media = Media::paginate(5);
$media->appends($request->all());
you can use laravel basic URLs instead of getting gallery images with URL get parameters.
something like this:
define Route like this
/items/gallery/{types}
then using it like
http://localhost:8000/items/gallery/glasses
in this case you don't get that error anymore

Laravel commenting with ajax

So I have a laravel commenting system which lets me conment using ajax. My current setup is simple. I have a field for comments and then my route is as follows:
Route::post(‘comment/{post_id}’, ‘CommentController#insert’);
And in my ajax url, I have given the same route with the post_id. I am giving the post id because I wanted to add the post id to my post_id column in my comments table. Also my ajax is in line.
Now my question is, I do not know how to add replies to a comment. I have to insert the comment_id to my replies table comment_id column because comment and replies are related. What confuses me is, if I created a lot of reply forms with a foreach loop for each comment, how can I pass all those comment ID to the ajax?
Say for an example this is my route for storing replies
Route::post(‘replies/{comment_id}’, ‘ReplyController#insert’);
This won’t be like comments that I will be passing only value for the parameter (post_id). This reply will have a lot of values for one parameter right? So how can I proceed with this. I am new to ajax and I am having a hard time trying to get the logic of this. Like I mentioned before, the confusion is that each reply will have a separate comment_id that I need to pass to the route parameter.
you should pass like below:
Route::post('/comment/{comment_id}/replies','ReplyController#insert');
You can try like this
View (here $comments and $comment->replies are assumed, you may have different)
<div class="post-comments">
<p>Comments</p>
#foreach($comments as $comment)
<p>{{$comment->text}}<p>
<label>Replies:</label>
<ul>
#foreach($comment->replies as $reply)
<li>{{$reply->text}}</li>
#endforeach
<form name="replyForm">
<input name="reply" />
<button type="button" onclick="replyComment('/comment/{{$comment->id}}/reply', this.form.reply)">Reply</button>
</form>
</ul>
#endforeach
</div>
Javascript
function replyComment(url, input){
console.log(url);
console.log(input.value);
//call ajax with this url and input value
}
Route
Route::post('comment/{comment_id}/reply', 'ReplyController#insert);
<input type="submit" style="float: right;" class="btn btn-primary" value="Comment" id="comment" data-url="/comment/{{$comment->id}}/replies" data-token="{{ csrf_token() }}" data-comment_id="{{$comment->id}}" >
assuming that you are fetching the $comment from controller.
even if you are adding button there is no need to add the <form>.
You have to pass post_id during reply .
Route like :
Route::`post(‘replies/{post_id}/{comment_id}’, ‘ReplyController#insert’);`
Then sort it those comment by inserting time .

Laravel 4 - Update Div Using Ajax

I'm using Laravel 4 and am trying to update a (#articles) div with the new articles that are retrieved from an ajax request. When I inspect the page and view the Network section, I can see the POST requests being fired off and it's not showing any errors (eg, articles appear to be returned). However, unfortunately, the #articles div is not being updated with the new information. Yet, if I do a browser refresh, the new articles are displayed.
Routes.php
Route::any("/dashboard/latest_sa", [
"as" => "dashboard/latest_sa",
"uses" => "DashboardController#latest_sa"
]);
controllers/DashboardController.php
Class DashboardController extends \BaseController
{
...
protected function latest_sa()
{
if( Request::ajax() )
{
// called via ajax
$articles = Articles::orderBy('published_at', 'desc')->paginate(20);
return json_decode($articles);
}
else
{
// fresh page load
$articles = Articles::orderBy('published_at', 'desc')->paginate(20);
return $articles;
}
}
...
}
app/views/dashboard/default.blade.php
...
#section("content")
// defined in /public/js/main.js
<script type="text/javascript">
callServer();
</script>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<h4>Latest Articles</h4>
<div class="articles">
<ul>
#foreach ($articles as $article)
<li>
<img src="{{ $article->user_image }}" alt="{{ $article->article_title }}" />
{{ $article->article_title }}
<div class="details">
<span class="author">{{ $article->author_name }}</span>
<span class="created">{{ Helpers::time_ago($article->published_at) }}</span>
<span class="symbol">{{ $article->symbol_title }}</span>
</div>
</li>
#endforeach
</ul>
</div>
{{ $articles->links() }}
</div>
...
/public/js/main.js
function callServer()
{
setInterval(function(){
$.ajax({
type: "POST",
url: "dashboard/latest_sa",
success:function(articles)
{
$(".articles").html(articles);
}
});
},5000);
}
JS is hardly my strong suit, so I'm not sure what I'm doing wrong here.
And, for clarity sake, the reason why I'm trying to update all of the articles in the div is so that the Helpers::time_ago method also gets called, instead of just fetching the new articles. This way, it properly shows how long ago the article was published (eg, less than a minute ago, a minute ago, a hour ago, a day ago, etc) without refreshing the page. Essentially, I'm trying to kill two birds with one stone; update the div with the most recent articles, and update the remaining article's published_at attribute using my Helpers::time_ago method. If there is a more effective / efficient way of doing this, feel free to correct me. This seems rather crude, but since it's only for personal use and will never be used for commercial purposes, it suits my needs (not that that excuses bad code).
Nonetheless, from my fairly basic understanding, the JS should be doing the following steps:
1) Fire a POST request off to the /dashboard/latest_sa route
2) Execute the DashboardController#latest_sa action
3) Return a DB collection of all $articles ordered by the latest published date, and paginated
4) Pass the $articles collection back to the JS success attribute (as articles)
5) Fire the anonymous function, with the articles collection as an argument
6) Update the corresponding inner HTML with the results from the articles collection
The logic sounds right, so I'm pretty sure this is going to be a human error (98% of the time it is, after all. lol). Hopefully, someone here will be able to see the (probably glaring) problem in the logic and point me in the right direction.
In the meantime, I'm going to keep toying around with it.
I look forward to your thoughts, ideas, and suggestions. TIA.
EDIT:
Well, I found one of the problems; the articles div is a class, and in the JS I'm referring to it as an id. I fixed that, and now after the timeInterval, the article's div is "updated" but no results are being displayed (none, zippo, nadda).
Yet, if I directly access the /dashboard/latest_sa URI I get the valid JSON response that I'm expecting. So, albeit I am closer, I am still missing something.
EDIT 2:
Okay, in the controller, I made some changes which can be seen above, where I am now doing a json_decode on the $articles, before returning them to be passed into the view. With that in place, the articles are showing back up again after the timeInterval has elapsed, however, the new articles and the published_at for the existing articles are not being updated. After reviewing Inspect -> Network, it shows that the server is responding with a 500 Internal Server Error from the ajax POST request.
Hrm... Seems like I'm going in circles. Sounds like a good time to take a break and go for a walk. ;)
EDIT 3:
Well, I modified my Helpers class and added in the following method to check if the $article is a json object.
public static function isJson($string)
{
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
app/views/dashboard/index.blade.php
#foreach ($articles as $article)
<?php
if( Helpers::isJson($article) )
{
$article = json_decode($article);
// dd($article) // when uncommented it returns a valid PHP object
}
?>
<!-- Iterate over the article object and output the data as shown above... -->
#endforeach
As you can see, (for the time being) inside of my view's foreach($articles as $article), I run Helpers::isJson($article) as a test and decode the object if it is json. This has enabled me to get passed the 500 Internal Server Error message, populate the articles div with the results on the initial load, and after the ajax POST request is fired off, I'm getting back a server response of 200 OK according to Inspect -> Network. However, after it updates the div, it doesn't show any articles.
Around, and around I go... I think it's time I take that break I keep murmuring about. ;)
Any thoughts, suggestions and / or ideas are greatly welcomed and appreciated.
At first, you should know that, when you return a collection from the controller/route, the response automatically turns in to a json response so, you don't need to use json_decode() and it won't work, instead, you may try something like this (from your controller for ajax):
$articles = Articles::orderBy('published_at', 'desc')->paginate(20);
return View::make('defaultAjax')->with('articles', $articles);
Since building the HTML in the client side using the json data received from server side would be tough for you so, you may return HTML from the server with the generated view instead of json, so you may try something like this in your success handler:
success:function(articles) {
$(".articles").html(articles);
}
Now create a view for ajax response without extending the template like this:
//defaultAjax.blade.php used in the controller for ajax response
<ul>
#foreach ($articles as $article)
<li>
<img src="{{ $article->user_image }}" alt="{{ $article->article_title }}" />
{{ $article->article_title }}
<div class="details">
<span class="author">{{ $article->author_name }}</span>
<span class="created">{{ Helpers::time_ago($article->published_at) }}</span>
<span class="symbol">{{ $article->symbol_title }}</span>
</div>
</li>
#endforeach
</ul>
{{ $articles->links() }}
Notice, there is no #extendds() or #section(), just plain partial view, so it'll be rendered without the template and you can insert the ul inside the .articles div. That's it.
$("#articles").html(articles); ->> $(".articles").html(articles);

Resources