JSON in Laravel

0

I would like to know how to send the query data in json through the controller and how the view should receive them.

Controller:

$dados = $req->all();

$query = "";

if($dados['filter'] == 1)
{

  $query = User::where('id','LIKE','%'.$dados['search'].'%');
}
else if($dados['filter'] == 2)
{

  $query = User::where('name','LIKE','%'.$dados['search'].'%');
}
else if($dados['filter'] == 3)
{

  $query = User::where('email','LIKE','%'.$dados['search'].'%');
}

return view('users.index')->with([$users->$query]);

View:

  @foreach($users as $user)
      <tr>
        <td>{{$user->id}}</td>
        <td>{{$user->name}}</td>
        <td>{{$user->email}}</td>
      </tr>
      @endforeach
    
asked by anonymous 29.05.2018 / 16:04

1 answer

0

Do as follows:

$dados = $req->all();

$query = "";

if($dados['filter'] == 1)
{

  $users = User::where('id','LIKE','"%'.$dados['search'].'%"')->get();
}
else if($dados['filter'] == 2)
{

  $users = User::where('name','LIKE','"%'.$dados['search'].'%"')->get();
}
else if($dados['filter'] == 3)
{

  $users= User::where('email','LIKE','"%'.$dados['search'].'%"')->get();
}

return view('users.index', compact('users'));

Your view may leave the same way.

I would advise you to take this out of Controller and separate it into another layer, a Service for example.

    
29.05.2018 / 23:54