Laravel 5.4: execute raw query and show data in view

I want to run a raw query that I wrote in my controller, and I want to show data from the database in my view.

This is my controller function:

public function unverified_jobs_page()
{
  $query = "SELECT jd.*, cd.`company_name`, jc.`category_title`, jt.`job_type_title`, cc.`city_name`
            FROM `job_details` AS jd
            JOIN `company_details` AS cd ON cd.`company_id`=jd.`company_id`
            JOIN `job_category` AS jc ON jc.`category_id`=jd.`category_id`
            JOIN `job_type` AS jt ON jt.`job_type_id`=jd.`job_type_id`
            JOIN `city` AS cc ON cc.`city_id`=jd.`city_id`
            WHERE jd.`is_verified`='NO'
            ORDER BY jd.`date_posted` DESC";

    $sql = General_model::rawQuery($query);

    return view('adminpanel.jobs.unverfied_jobs',compact($sql));        

}

This is my rawQuery () model function

 public static function rawQuery($query)
 {
 return DB::select( DB::raw($query) );  
 }

It's my opinion:

 <table class="table table-striped border-top" id="sample_1">
                    <thead>
                        <tr> 
                        <th>JOB ID </th>
                        <th>TITLE</th>
                        <th>COMPANY</th>
                        <th>CITY</th>
                        <th>DATE POSTED</th>
                        <th>CLOSING DATE</th>
                        <th>&nbsp;</th>
                        </tr>
                    </thead>
                    <tbody>

                       @foreach($sql as $d)

                       <tr>
                       <td>{{$d->job_id}}</td>
                       <td>{{$d->job_title}}</td>
                       <td>{{$d->company_name}}</td>
                       <td>{{$d->city_name}}</td>
                       <td>{{$d->date_posted}}</td>
                       <td>{{$d->expiry_date}}</td>
                        <td><a class='btn btn-info' href='#'>DETAILS</a></td>
                       </tr>

                       @endforeach
                    </tbody>
                </table>  

Now the problem is that every time I try to start the page, it causes the following error:

ErrorException in 10f46e45beef75fdd05b083aa636ae7821fe6936.php line 30:
Undefined variable: sql (View: C:\AppServ\www\jobs\jobs\unverfied_jobs.blade.php)

Please, help.

+4
source share
1 answer

You need to pass the variable $sqlto your view properly.

Try

compact('sql');

+1
source

Source: https://habr.com/ru/post/1680573/


All Articles