Leguam
Leguam

Reputation: 1212

Laravel getting id from stored object

I have a company table and an attributes table with all sorts of value in it.

One company hasMany attributes and an attribute belongsTo a company.

Now I have a value inside the attributes table with a 'account_nr_start' (for example, when a new user is added to a company its account_id starts counting up from 1000).

Lets say I create a new Company, [id=5], with account_nr_start 1101(reference number) it should input this:enter image description here

But instead of that it upload a rule without a company_id, which is clear because when I create a new company it doesn't have a company_id to get, but how can I get the ID inside the store function so it can still send it to the attribute table?

enter image description here

Controller:

public function __construct(Company $company, User $user)
{
    if(Auth::user()->usertype_id == 7)
    {
        $this->company = $company;
    }
    else
    {
        $this->company_id = Auth::user()->company_id;
        $this->company  = $company->Where(function($query)
        {
            $query->where('id', '=', $this->company_id )
                ->orWhere('parent_id','=', $this->company_id);
        }) ;
    }

    $this->user = $user;

    $this->middleware('auth');

    $page_title = trans('common.companies');
    view()->share('page_title', $page_title);
}


public function create(Company $company, CompaniesController $companies)
{
    $companies = $companies->getCompaniesName(Auth::user()->company_id);

    return view('company.create', ['company' => $company, 'id' => 'edit', 'companies' => $companies]);
}


public function store(CreateCompanyRequest $request, Company $company, Attribute $attribute)
{
    $company->create($request->all());

    dd($company->id);

    $attribute->create($request->only('company_id', 'attribute_nr', 'value'));

    return redirect()->route('company.index');
}

I tried to just dd($company->id); but that doesn't work, result will benull`

Upvotes: 0

Views: 5731

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

To get id of created object, you should run:

$company = $company->create($request->all());

dd($company->id);

instead of

$company->create($request->all());

dd($company->id);

You can now pass id of company when creating Attribute this way:

$attribute->create(array_merge($request->only('attribute_nr', 'value'), ['company_id' => $company->id]);

Upvotes: 2

Related Questions