Search code examples
phplaravellaravel-5laravel-5.3

Store data in 2 different tables in Laravel Controller


can i have a little help please! I am trying to make a system with businesses and users who can access this businesses. Users are related to businesses in DB with a column called 'id_business', which is the id of the business that this user can manage. At first I create users and I set the value of 'id_business' by default 0. Then when when I create a new business I set the name of the business and from a dropdown list (with users that has the value of 'id_business=0') I choose the user for this business. Now my question is, how can I store in one form the new business and set the value of 'id_business' in users table like the id of the new business i just created. I take users from this is list:

<select name="id_business" class="form-control input-xlg">
 <option value="">Select User </option>
 @foreach($users as $user)
 <option value="{{$user->id}}">{{$user->name}}</option>
 @endforeach
</select>

And in my controller I have gone this far, but it is not working:

public function store(Request $request)
{

    $businesses = new Businesses();
    $businesses->name = $request->name;
    $businesses->user_create_id = Auth::user()->id;

    $user= Businesses_Users::first();

    if($businesses->save())
    {
        $request->id_business;
        $user->id = Businesses_Users::find($request->id_business);

        $user->id_business = $businesses->id;


        return redirect()->route('businesses',$businesses->id)->with('success', sprintf('Business successfully created.'));
    }
    else
    {
        return redirect()->back()->with('error', sprintf('An unexpected error occurred.Please fill a report form on this issue.'));
    }

}

Thanks in advance.


Solution

  • Missing save() function

    $user = Businesses_Users::find($request->id_business); 
    $user->id_business = $businesses->id;
    $user->save();