Creating hyperlinks of each object from an array of objects

Creating hyperlinks of each object from an array of objects

ratchadewiratchadewi Posts: 3Questions: 2Answers: 0

Hi everyone,
I'm still a novice, learning datatables for laravel, I'd like to request some assistance please. So, I have an array of objects as a data source, I'd like to create a hyperlink for each of those objects using AJAX, is it possible?
I've tried searching some tutorials regarding how to make hyperlink with AJAX, it's working if it's not an array though.

In my controller, here is the code

if ($request->ajax()) {
    $query = StudentGuardian::with([  'related_students'])->select(sprintf('%s.*', (new StudentGuardian())->table));
    $table = Datatables::of($query);
    $table->editColumn('related_students', function ($row) {
                $students = json_decode($row->related_students, true);
                return $students;
     });
    return $table->make(true);

and in the blade,

columns: [
     { data: 'related_students[, ].full_name' },
]

Now I'm trying to create urls for each nested data. Can anyone help me please?

Answers

  • ratchadewiratchadewi Posts: 3Questions: 2Answers: 0

    So I've found this tutorial with live example
    I've modified the blade

    columns: [
         { data: 'related_students[, ].full_name' },
    ]
    

    to

    columns: [
         data: 'related_students[, ].id',
         render: function ( data,type,row,meta ) {
                        var urls='';
                        console.log(data);
                        for(i=0; i<data.length; i++){
                           urls += '<a href="/students/'+data[i]+'">'+data[i]+'</a>'
                        }
                        return urls;
                    },
    ]
    

    As the result, I do now have in each cell separate urls for the nested data. BUT, the id (data[i]) doesn't match with the id of 'related_students[, ].id'

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    Can you post an example of your data so we can see the structure?

    Kevin

  • allanallan Posts: 63,531Questions: 1Answers: 10,474 Site admin

    One other thing I just spotted - remove the , in the data property:

    data: 'related_students[].id',
    

    If you put a string in between the brackets, it will automatically do a join with the characters in between the brackets used as the joiner. No characters between them will give you an array.

    So at the moment I think that you are doing a for loop over a string, rather than the expected array of ids.

    Allan

Sign In or Register to comment.