beginner_luck's avatar

How to create a link in javascript with laravel

can someone help me on how I can create a link in Javascript with Laravel. Or how can I convert this code to javascript?("{{ route('blog.single', $post->slug) }}") because I wanted to show the URL of every single post I have used in that code, I don't know what's wrong but the URL only shows me the last post that I have created, when everytime I click the VIEW button the one that keeps on showing is the slug/url in the last post I created.

This is my code for getting the slug in database

 data-slug="{{$post->slug}}"

This is my code in passing it using jQuery.

$(document).on('click', '.show-post', function() {

  var slug = $(this).attr('data-slug');
   $('#show-slug').html(slug);
   $('.show-single-post').css('display','block');
   $('.posts-table').css('display','none');

});

And my code for creating the URL.

{{ route('blog.single', $post->slug) }}

The blog.single, is my single.blade.php that shows the single post.

0 likes
4 replies
wilburpowery's avatar
let tag = document.createElement('a');
tag.setAttribute('href', 'https://google.com');

Is that what you're looking for?

dleroari's avatar

It feels like you want something like php artisan route:list. It shows you all the routes you have in your application.

toby's avatar

You could also create a mutator inside your model like this:

// in your eloquent model

public function getLinkAttribute() {
    return route('posts.show', $this);
}

Then you can create the link like: {{ $post->link }}(In your blade file).

Maybe you'll also need this custom accessor to your model's $appends-attribute: protected $appends = ['link']; if you want to use this data from a JSON response or something like this.

Please or to participate in this conversation.