Problem with select in my controller

Asked

Viewed 44 times

0

Hello, I’m making Join between two table to display the user name in the view, but this giving the following error:

Call to a member function select() on string

My controller:

$postagens = Postagens::all()->sortByDesc('created_at')
    ->join('users','users.id' , '=', 'postagens.usuario' )
    ->select('users.name as nomeusuario')
    ->get();
    return view('index',compact('postagens'));

The view:

@foreach ($postagens as $pubs)
@postagens()
        @slot('titulo')
            {{$pubs['nomePost']}}
        @endslot
    @slot('descricao')
        {{$pubs['descricao']}}
    @endslot
    @slot('dia')
        {{$pubs['created_at']}}
    @endslot

    @slot('id')
        {{$pubs['nomeusuario']}}
    @endslot        
@endpostagens
@endforeach

1 answer

4


The function all() is to return a collection of values obtained from your database. So when you declare Postagens::all(), will be returned a collection of all existing records in the configured table.

SELECT * FROM postagens

Note that in your code, you use the method join(), this method belongs to the Query Builder of Laravel, so to use it your code must be that way.

use Illuminate\Support\Facades\DB;

...

$postagens = DB::table('postagens') //Nome da tabela postagens
    ->select('users.name as nomeusuario')
    ->join('users','users.id','=','postagens.usuario')
    ->orderBy('postagens.created_at', 'desc')
    ->get();

To use your model for the query you need to use the Querying Relations of the Eloquent ORM.

  • gave it now: Join() expects at Most 2 Parameters, 4 Given

  • I have now given: Call to Undefined method Illuminate Database Eloquent Builder::sortByDesc()

  • @joaogabriel97, I didn’t even notice the error of the function you wrote. It’s not sortByDesc but yes orderBy where this is defined which field and type of the order. Look at documentation: https://laravel.com/docs/5.8/queries#Ordering-grouping-limit-and-offset

  • @joaogabriel97, solved your problem?

Browser other questions tagged

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