1

this is my website model

  class Website extends Model
{
    protected $table = 'website';

   public function links()
   {
    return $this->hasMany('App\Website_links')->where('crawler_status',1);
   }

}

and controller code

 if(Request::ajax()){

        $validator = Validator::make(Request::all(), [
            'page' => 'required',
        ]);
        if($validator->fails()){
            return Response::json(['success'=>false,'error'=>$validator->errors()->toArray()]);
        }

        $page = Request::get('page');
        $websites_data = Website::where('user_id',Auth::id())->skip(3*($page-1))->take(3)->get();
        return Response::json(['success'=>true,'success_data'=>$websites_data]);
    }

and javascrpit code

$(result.success_data).each(function( index,el) {
                console.log(el.project_name,el.website_url,el.links);
            });

here i am getting undefined on el.links. in my html i am getting it perfect like this

@foreach($data as $website)
                    <tr>
                        <td>{{$website['project_name']}}
                        </td>
                        <td><a href="{{$website['website_url']}}">{{$website['website_url']}}</a></td>
                        <td>{{count($website->links)}}</td></tr>
@endforeach

i want to count el.links in javascript like i have done in html.in javascript first two values project_name and website_url is coming perfectly.

2 Answers 2

3

You have to load the relationship to get it included in the JSON output.

Eager load it....

$websites_data = Website::with('links')->where('user_id',Auth::id())->skip(3*($page-1))->take(3)->get();

or lazy load it

$websites_data = Website::where('user_id',Auth::id())->skip(3*($page-1))->take(3)->get();
$websites_data->load('links');
Sign up to request clarification or add additional context in comments.

Comments

0

use

var obj = JSON.parse(el);
console.log(obj.project_name,obj.website,el.links)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.