Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to return id of socials table?

I have three migrations for table. socials, users, social_networks.

socials

public function up()
{
    Schema::create('socials', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
}

users

public function up()
{
        Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('image')->nullable();
        $table->string('first_name')->nullable();
        $table->string('last_name')->nullable();
        $table->string('job_title')->nullable();
        $table->boolean('gender')->nullable();
        $table->boolean('marital')->nullable();
        $table->bigInteger('soldier_id')->unsigned()->nullable();
        $table->foreign('soldier_id')->references('id')->on('soldiers')->onDelete('cascade');
        $table->integer('birth_date_day')->nullable();
        $table->bigInteger('month_id')->unsigned()->nullable();
        $table->foreign('month_id')->references('id')->on('months')->onDelete('cascade');
        $table->integer('birth_date_year')->nullable();
        $table->string('mobile')->nullable();
        $table->string('telephone')->nullable();
        $table->string('website')->nullable();
        $table->string('state_name')->nullable();
        $table->string('city_name')->nullable();
        $table->bigInteger('country_id')->unsigned()->nullable();
        $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
        $table->bigInteger('state_id')->unsigned()->nullable();
        $table->foreign('state_id')->references('id')->on('states')->onDelete('cascade');
        $table->bigInteger('city_id')->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
        $table->text('address')->nullable();
        $table->text('description')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

social_networks

public function up()
{
    Schema::create('social_networks', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('related_id');
        $table->timestamps();
    });

    Schema::create('social_user', function (Blueprint $table) {
        $table->bigInteger('social_id')->unsigned();
        $table->foreign('social_id')->references('id')->on('socials')->onDelete('cascade');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->primary(['social_id' , 'user_id']);
    });
}

I already added to display the social network in the socials table.

socials table

socials table

Display select option

select option

And then I successfully saved the information.

users table

users table

And

social_networks table

[social_networks table4

And

social_user table

social_user

So now that I have saved successfully, How can I display it?

HomeController.php

public function index()
{
    $socials = Social::all();
    return view('Home.test', compact('socials'));
}

User.php

public function socials()
{
    return $this->belongsToMany(Social::class);
}

public function socialNetworks()
{
    return $this->hasMany(SocialNetwork::class);
}

Social.php

public function users()
{
    return $this->belongsToMany(User::class);
}

test.blade.php

<!doctype html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="{{ asset('themes/css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ asset('themes/css/bootstrap.min-rtl.css') }}">
    <link rel="stylesheet" href="{{ asset('themes/css/style.css') }}">
    <link rel="stylesheet" href="{{ asset('themes/fontawesome/css/all.min.css') }}">
    @yield('style')
    <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" type="image/x-icon"/>
    <title>{{ config('app.name') }}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
    <div class="container">
        <a class="navbar-brand" href="{{ route('index') }}">
            {{ config('app.name') }}
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">

            <!-- Right Side Of Navbar -->
            <ul class="navbar-nav mr-auto">
                <!-- Authentication Links -->
                @guest
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">{{ __('ورود') }}</a>
                    </li>
                    @if (Route::has('register'))
                        <li class="nav-item">
                            <a class="nav-link" href="{{ route('register') }}">{{ __('ثبت نام') }}</a>
                        </li>
                    @endif
                @else
                    <li class="nav-item dropdown">
                        <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                            {{ Auth::user()->name }} <span class="caret"></span>
                        </a>

                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="{{ route('logout') }}"
                               onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                {{ __('خروج') }}
                            </a>

                            <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none;">
                                @csrf
                            </form>
                        </div>
                    </li>
                @endguest
            </ul>
        </div>
    </div>
</nav>
<div class="container">
    <form id="basic-information" method="post" enctype="multipart/form-data" action="{{ route('update', auth()->id()) }}">
        @csrf
        @method('put')
        <div class="row bg-white p-3 mb-5">
            <div class="col-md-2">
                <input name="image" onchange="previewFile()" type="file" class="d-none">
                @if (auth()->check() && auth()->user()->image)
                    <img src="{{ asset('images/users/'.auth()->user()->image) }}"  id="dialog" class="img-fluid rounded-circle cursor-pointer">
                @else
                    <img src="{{ asset('images/avatar.png') }}" id="dialog" class="img-fluid cursor-pointer">
                @endif
            </div>
            <div class="col-md-10">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="first_name">نام</label>
                            <input type="text" class="form-control" value="{{ auth()->user()->first_name }}" id="first_name" name="first_name">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="last_name">نام خانوادگی</label>
                            <input type="text" class="form-control" value="{{ auth()->user()->last_name }}" id="last_name" name="last_name">
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="job_title">عنوان شغلی رزومه</label>
                            <input type="text" class="form-control" id="job_title" value="{{ auth()->user()->job_title }}" name="job_title">
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="gender">جنسیت</label>
                            <select id="gender" name="gender" class="form-control">
                                <option value="1" {{ auth()->user()->gender == 1 ? 'selected' : '' }}>مرد</option>
                                <option value="0" {{ auth()->user()->gender == 0 ? 'selected' : '' }}>زن</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="marital">وضعیت تاهل</label>
                            <select id="marital" name="marital" class="form-control">
                                <option value="0" {{ auth()->user()->marital == 0 ? 'selected' : '' }}>مجرد</option>
                                <option value="1" {{ auth()->user()->marital == 1 ? 'selected' : '' }}>متاهل</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="soldier_id">وضعیت سربازی</label>
                            <select id="soldier_id" name="soldier_id" class="form-control">
                                @foreach($soldiers as $soldier)
                                    <option value="{{ $soldier->id }}" {{-- auth()->user()->resume->soldier->id == $soldier->id ? 'selected' : '' --}}>
                                        {{ $soldier->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="form-group">
                            <label for="birth_date_day">تاریخ تولد</label>
                            <select id="birth_date_day" name="birth_date_day" class="form-control">
                                @for($i = 1; $i <= 31; $i++)
                                    <option {{ auth()->user()->birth_date_day == $i ? 'selected' : ''}} value="{{ $i }}">{{ $i }}</option>
                                @endfor
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="month_id">ماه</label>
                            <select id="month_id" name="month_id" class="form-control">
                                @foreach($months as $month)
                                    <option value="{{ $month->id }}" {{ optional(auth()->user()->month)->id == $month->id ? 'selected' : '' }}>
                                        {{ $month->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label for="birth_date_year">سال</label>
                            <select id="birth_date_year" name="birth_date_year" class="form-control">
                                @for ($i = 1300; $i < 1400; $i++)
                                    <option {{ auth()->user()->birth_date_year == $i ? 'selected' : '' }} value="{{ $i }}">{{ $i }}</option>
                                @endfor
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <b>اطلاعات تماس</b>
        <div class="row bg-white p-3 mb-5">
            <div class="col-md-3">
                <div class="form-group">
                    <label for="email">ایمیل</label>
                    <input value="{{ auth()->user()->email }}" type="text" id="email" name="email" class="form-control">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="mobile">موبایل</label>
                    <input value="{{ auth()->user()->mobile }}" type="text" id="mobile" name="mobile" class="form-control">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="telephone">تلفن</label>
                    <input value="{{ auth()->user()->telephone }}" type="text" id="telephone" name="telephone" class="form-control">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label for="website">وبسایت</label>
                    <input value="{{ auth()->user()->website }}" type="text" id="website" name="website" class="form-control">
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label for="country_id">کشور</label>
                    <select id="country_id" name="country_id" class="form-control">
                        <option></option>
                        @foreach($countries as $country)
                            <option {{ optional(auth()->user()->country)->id == $country->id ? 'selected' : '' }} value="{{ $country->id }}">
                                {{ $country->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label for="state_id">استان</label>
                    <select id="state_id" name="state_id" class="form-control">

                    </select>
                    <input type="text" name="state_name" value="{{ auth()->user()->state_name }}" id="state_id" class="form-control d-none">
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label for="city_id">شهر</label>
                    <select id="city_id" name="city_id" class="form-control">

                    </select>
                    <input type="text" name="city_name" value="{{ auth()->user()->city_name }}" id="city_id" class="form-control d-none">
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="address">آدرس</label>
                    <input value="{{ auth()->user()->address }}" type="text" id="address" name="address" class="form-control">
                </div>
            </div>
        </div>
        <b>توصیف خلاصه</b>
        <div class="row bg-white p-3 mb-5">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="description">توصیف خلاصه</label>
                    <textarea id="description" name="description" class="form-control">{{ auth()->user()->description }}</textarea>
                </div>
            </div>
        </div>
        <b>شبکه اجتماعی</b>
        <div class="mb-2 bg-white p-3 mb-5">
            <div class="row p-3" id="showSocial">

            </div>
            <div class="w-100 text-center">
                <p>شبکه اجتماعی دیگری را اضافه کنید.</p>
                <a id="addSocial" class="bg-primary text-white pt-2 pb-2 pl-3 pr-3 rounded-circle cursor-pointer">
                    <i class="fas fa-plus"></i>
                </a>
            </div>
        </div>
        <div class="form-group mb-5">
            <button type="submit" class="btn btn-success">ذخیره</button>
        </div>
    </form>
</div>
<script src="{{ asset('themes/js/jquery-3.5.1.min.js') }}"></script>
<script src="{{ asset('themes/js/popper.min.js') }}"></script>
<script src="{{ asset('themes/js/bootstrap.min.js') }}"></script>
<script>
    $(document).ready(function() {
        let countSocial = 1;
        $('#addSocial').click(function () {
            countSocial++;
            dynamicSocial(countSocial);
        });
        //dynamicSocial(countSocial);
        function dynamicSocial (number) {
            let html = '' +
                '<div class="col-md-6 position-relative">\n' +
                '<i class="fas fa-times text-danger position-absolute"></i>' +
                '<div class="row">\n' +
                '<div class="col-md-4">\n' +
                '<div class="form-group">\n' +
                '<label for="social_id">شبکه اجتماعی</label>\n' +
                '<select id="social_id" name="social_id[]" class="form-control">\n' +
                '@foreach($socials as $social)\n'+
                '<option value="{{ $social->id }}">\n' +
                '{{ $social->name }}\n' +
                '</option>\n' +
                '@endforeach\n ' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-8">\n' +
                '<div class="form-group">\n' +
                '<label for="related_id">آی دی مرتبط</label>\n' +
                '<input id="related_id" name="related_id[]" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>';
            $('#showSocial').append(html);
        }
        showDynamicSocial();

        function showDynamicSocial() {
            let html = '' +
                '<div class="col-md-6 position-relative">\n' +
                '<i class="fas fa-times text-danger position-absolute"></i>' +
                '<div class="row">\n' +
                '<div class="col-md-4">\n' +
                '<div class="form-group">\n' +
                '<label for="social_id">شبکه اجتماعی</label>\n' +
                '<select id="social_id" name="social_id[]" class="form-control">\n' +
                '@foreach($socials as $social)\n'+
                '<option value="{{ $social->id }}" {{ auth()->user()->socialNetworks->contains($social->id) ? 'selected' : '' }}>\n'+
                '{{ $social->name }}\n' +
                '</option>\n' +
                '@endforeach\n ' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-8">\n' +
                '<div class="form-group">\n' +
                '<label for="related_id">آی دی مرتبط</label>\n' +
                '<input id="related_id" value="{{ auth()->user()->socialNetworks->related_id }}" name="related_id[]" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>';
            $('#showSocial').append(html);
        }
    });
</script>

</body>
</html>

I want to return related_id from social_networks table and return social_id from socials table.

page

0 likes
8 replies
shahr's avatar
Level 10

@automica

What fields should I add in tables? Rename yourself.

Rename yourself. Either add or remove.

automica's avatar
automica
Best Answer
Level 54

@oxbir u think you can simplify this:

Your need to define a relationship to Social from User

// User Model

public function socials()
{

return $this->belongsToMany(Social::class)->withPivot('link');

}

To store the id of their account (which I assume you are trying to store @name for twitter etc) just add another column on your social_user table.

    Schema::create('social_user', function (Blueprint $table) {
        $table->bigInteger('social_id')->unsigned();
        $table->foreign('social_id')->references('id')->on('socials')->onDelete('cascade');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
	$table->string('link'); // what you've called related_id
        $table->primary(['social_id' , 'user_id']);
    });

the relationship with social and link is a hasOne to User so can be stored here and accessed by using ->pivot->link; // or whatever your field name is

so from blade:

@foreach($user->socials as $social)
<li> {{ $social->id }} {{ $social->name }} {{ $social->pivot->link }} </li>
@endforeach;

this should get you social name and the link they have added

see 'Retrieving Intermediate Table Columns' section in https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

1 like
shahr's avatar
Level 10

I get this error.

Undefined variable: user

shahr's avatar
Level 10

@automica

🌸🌸🌸🌸🌸🌸🌸🌸🌸🌸🌸

Thank you . only have a question How to save it link

Please or to participate in this conversation.