Search code examples
jqueryajaxlaravellaravel-bladelaravel-controller

Ajax_JQUERY and Laravel Controller?


I am new in Laravel,i need to add edit and show button via in Controller here is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class LiveSearch extends Controller
{
    function index() {
        return view('live_search');
    }

    function action(Request $request) {
     if($request->ajax()) {
        $output = '';
        $query = $request->get('query');

        if($query != '') {
           $data = DB::table('students')
             ->where('student_name', 'like', '%'.$query.'%')
             ->orWhere('student_address', 'like', '%'.$query.'%')
             ->orWhere('student_registration', 'like', '%'.$query.'%')
             ->orderBy('student_name', 'desc')
             ->get();
        } else {
           $data = DB::table('students')
             ->orderBy('student_name', 'desc')
             ->get();
        }

        $total_row = $data->count();

        if($total_row > 0) {
           foreach($data as $row) {
              $output .= '
                <tr>
                   <td>'.$row->student_name.'</td>
                   <td>'.$row->student_address.'</td>
                   <td>'.$row->student_registration.'</td>
                   <td>'.$row->id.'</td>
                   <td>' <a  href="{{ URL::to(student/ ".$row->id." /edit) }}">Edit</a>'
                         <a href={{ URL::to(student/  '.$row->id.') }}>Show</a></td>
                </tr>';
           }
        } else {
           $output = '
             <tr>
                <td align="center" colspan="5">No Data Found</td>
             </tr>';
        }

        $data = array(
          'table_data'  => $output,
          'total_data'  => $total_row
        );

        echo json_encode($data);
     }
   }
}

PROBLEM Here is the problem i dont know how to add id with edit button and show along with bootstrap class btn btn success// it fetches all the data from student table but i don't know how to add could you pleaes guied me what to do, i search a lot but it not solve my problem thanks


Solution

  • The problem is you are not passing the url correctly.

    $output .= '
                <tr>
                   <td>'.$row->student_name.'</td>
                   <td>'.$row->student_address.'</td>
                   <td>'.$row->student_registration.'</td>
                   <td>'.$row->id.'</td>
                   <td>
                       <a href="'.url("student/".$row->id."/edit").'">Edit</a>
                       <a href="'.url("student/".$row->id).'">Show</a>
                   </td>
                </tr>';
    

    If your url is named route, like this:

    Route::get('/live_search', 'LiveSearch@index')->name('live.search');
    

    You can specify like this too

    route('live.search')
    

    I'm not sure about your routes, change it if you have different route.