Skip to content
Advertisement

Data output from the database

I have a select and I want to output data from the DB

            <select class="select-css" name="title" required="">
                <option selected="" value="" disabled="">Выберите сервер</option>
                @foreach($guilds as $guild)
                    <option value="{{$guild->id}}">{{$guild->name}}</option>
                @endforeach
            </select>

In CreateController I wrote this

$guilds = User::with('guilds')->get('id') === Auth::user()->id;

I have a UserGuild database

class UserGuild extends Model
{
    public function user(){
        return $this->hasMany(User::class);
    }
    public function guild(){
        return $this->belongsToMany(Guild::class);
    }
        Schema::create('user_guilds', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->unsignedBigInteger('guild_id')->nullable();
            $table->index('user_id','user_guild_user_idx');
            $table->index('guild_id','user_guild_guild_idx');
            $table->foreign('user_id','user_guild_user_fk')->on('users')->references('id');
            $table->foreign('guild_id','user_guild_guild_fk')->on('guilds')->references('id');

And I have such a mistake

ErrorException
foreach() argument must be of type array|object, bool given (View: C:OpenServerdomainslocalhostsite-rtsresourcesviewsmainservercreate.blade.php)

I need to output to select what is in the User Guide database, but at the same time where {{$guild->name}}and value were were values from the Guild database

I also tried using foreach, but it doesn’t suit me for further work.

                @foreach($users as $user)
                    @foreach($user->guilds as $guild)
                        @if(Auth::user()->id === $user->id)
                              <option value="{{$guild->id}}">{{$guild->name}}</option>
                        @endif
                    @endforeach
                @endforeach

Advertisement

Answer

Assuming the model and migration is correct, the problem lies in query which in this case returning boolean instead of collection, and then foreach in the blade view get passed boolean as an argument instead of collection because of this it will throw an error.

So instead using these condition === Auth::user()->id;, you can use where method to get data from database that correspond with id you want.

$guild = User::with('guilds')->where('id', Auth::user()->id)->get();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement