我想存储一个数组中的数据,并且需要将这些实体的ID存储在另一个数组中

时间:2019-06-18 14:01:09

标签: arrays laravel-5 eloquent

!!!更新!!!

问题由我自己解决,更新的工作代码如下:

我试图在Laravel中存储诸如$locations = "khulna, dhaka"之类的数组中的数据。但是,位置表中的位置不应重复。稍后,我需要在另一个数组中找到这些位置的ID(如果它们已经在表中或已经新插入),以便可以将它们与用户连接。

public function addUser(Request $request)
    {
        $locations = $request->location;

        // need to store in the table without duplicating
        // Update - Now I am able to store data without duplicating
        foreach($locations = explode(',', $locations) as $location)
        {
            Location::firstOrCreate([
                'name'  => $location,
                'slug'  => Str::slug($location),
            ]);
        }

        // need the IDs of the locations in another array - (Solved) 
        foreach($locations as $location)
        {
            $location = Location::where('slug', Str::slug($location))->first();
            $location_ids[] = $location->id;
        } 

            $user = User::create([
                'name'              => $request->name,
                'email'             => $request->email,
            ]);

            // Because I need to attach those locations with user
            $user->locations()->attach($location_ids);


        return redirect('users');
    }

0 个答案:

没有答案