JSON in Laravel

Asked

Viewed 285 times

0

I wanted to know how to send the data of the query 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
  • How did you put the Return of your function in the controller? You just need to put the view/('view')->with([$var_para_chamar_no_blade -> $query]);

  • Got it, I’ll be trying

  • Luiz, look at the Review I edited in the publication

  • Luiz, I put, but this giving Object error

  • It is not necessary to use Audacoes here if you want to know more why, read: https://pt.meta.stackoverflow.com/q/846/28595

  • Thank you! I’m new here

  • failed to assign the variable p to call in Blade, try like this: Return view('users.index')->with(['users' -> $query]);

  • he gives this error: Object of class Illuminate Database Eloquent Builder could not be converted to string

  • good.. think q missed the ->get() at the end. updates the return to: ->with(['users' -> $query->get()]);

  • is right: https://laravel.com/docs/5.5/queries#json-Where-clauses

  • Man, same mistake

  • face has some bo in query ai, exchange LIKE for like, if not scroll try to see here q is the same BO. https://answall.com/questions/165859/object-of-class-illuminate-database-eloquent-builder-could-not-be-converted-to-s

Show 7 more comments

1 answer

1

Do it this way:

$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 can leave in the same way.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.