Home>

When I click the apply button in laravel 5.6, I want to skip the information in the company_user intermediate table with the company table id as company_id and the users table id as user_id. I don't know which code can be inserted into the intermediate table by writing which code on which page.

Error message
if ($request->method () == 'OPTIONS') {
            return (new Route ('OPTIONS', $request->path (), function () use ($methods) {
                return new Response ('', 200, ['Allow' =>implode (',', $methods)]);
            }))->bind ($request);
        }
        $this->methodNotAllowed ($methods);
    }
    / **
     * Throw a method not allowed HTTP exception.
     *
     * @param array $others
     * @return void
     *
     * @throws \ Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
     * /
    protected function methodNotAllowed (array $others)
    {
        throw new MethodNotAllowedHttpException ($others);
    }
    / **
     * Get routes from the collection by method.
     *
     * @param string | null $method
     * @return array
     * /
    public function get ($method = null)
    {
        return is_null ($method)? $this->getRoutes (): Arr :: get ($this->routes, $method, []);
    }
    / **
     * Determine if the route collection contains a given named route.
     *
     * @param string $name
     * @return bool
     * /
    public function hasNamedRoute ($name)
Arguments

Error message
""

Applicable source code

↓ This is the Form part of the companies.show page.

{!! Form :: open (['url' =>['/ companies/{{$company->id}}'], 'method' =>'POST']) !!}
{{csrf_field ()}}
{{Form :: hidden ('company_id', '$company->id')}}
{{Form :: hidden ('user_id', 'Auth :: user ()->id')}}
{{Form :: submit ('apply', ['class' =>'btn btn-danger'])}}
{!! Form :: close () !!}
Tried

《In store section of companies controller page》

public function store (Request $request)
    {
        $company = Company :: find ($request->input ('company_id'));
        $user = User :: where ('user_id', Auth :: user ()->id)->get ();
        if ($user&&$company) {
            $company->users ()->attach ($user->id);
        }
    }


I tried to describe.

《company model ↓》

<? php
namespace App;
use Illuminate \ Database \ Eloquent \ Model;
class Company extends Model
{
    protected $fillable = array ('country_id', 'title', 'description');
    public function country () {
        return $this->belongsTo ('App \ Country');
    }
    public function user ()
    {
        return $this->belongsToMany ('App \ User')->using ('App \ Company_User');
    }

}

<< in the user model page ↓ >>

&lt;? php
namespace App;
use Illuminate \ Notifications \ Notifiable;
use Illuminate \ Foundation \ Auth \ User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    / **
     * The attributes that are mass assignable.
     *
     * @var array
     * /
    protected $fillable = [
        'name', 'email', 'password'
    ];
    / **
     * The attributes that should be hidden for arrays.
     *
     * @var array
     * /
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function company () {
        return $this-&gt;belongsToMany ('App \ Company')-&gt;using ('App \ Company_User');
    }
}

Also $php artisan make: migration create_company_user_table
Create an intermediate table with the migration file

public function up ()
    {
        Schema :: create ('company_user', function (Blueprint $table) {
            $table-&gt;increments ('id');
            $table-&gt;integer ('company_id')-&gt;unsigned ();
            $table-&gt;foreign ('company_id')-&gt;references ('id')-&gt;on ('companies');
            $table-&gt;integer ('user_id')-&gt;unsigned ();
            $table-&gt;foreign ('user_id')-&gt;references ('id')-&gt;on ('users');
            $table-&gt;timestamps ();
        });
    }


After writing like this, $php artisan migrate is done and migrate is done normally, but
When I try to insert information into an intermediate table using $php artisan tinker, I get an error that the table is not found.

  • Answer # 1

    return $this->belongsToMany ('App \ User')->using ('App \ Company_User');
    return $this->belongsToMany ('App \ Company')->using ('App \ Company_User');

    These->using ()are not required.
    You must specify a table, not a model (you don't need to write it if you follow the naming convention, but I'll skip that).

    https://readouble.com/laravel/5.6/en/eloquent-relationships.html#many-to-many

    return $this->belongsToMany ('App \ User', 'company_user');
    return $this->belongsToMany ('App \ Company', 'company_user');

    This is fine.

    https://readouble.com/laravel/5.6/en/eloquent-relationships.html

      

    To attach a role to a user by inserting a record into an intermediate table that connects the model, use the attach method.

    $user = User :: where ('user_id', Auth :: user ()->id)->get ();

    Here is an error iffind ()is not used.
    This is becausewhere ()->get ()returns a collection type instead of a model type.

    if ($user&&$company) {

    I personally usefindOrFailbecause this criterion is not beautiful.

    https://readouble.com/laravel/5.6/en/eloquent.html

      

    You may want to throw an exception when the model is not found. This is especially useful in routes and controllers. The findOrFail method and the firstOrFail method, which retrieves the first result of a query, throws an Illuminate \ Database \ Eloquent \ ModelNotFoundException exception if no such record is found.

    Auth :: user ()->idis also smarter usingAuth :: id ()

    public function store (Request $request)
    {
        $company = Company :: findOrFail ($request->input ('company_id'));
        $user = User :: findOrFail (Auth :: id ());
        $company->users ()->attach ($user->id);
    }