Bhavin Shah
Bhavin Shah

Reputation: 2482

How to get array data in url in Laravel 5.2?

This is my Route.php

Route::get('users/{user_name}/{source}/{destination}/{members}' , 'Userscontroller@index');

I want array of members in url. How can I get it and How can I pass to index() in UsersController.

Here is my UsersController.php

public function index($user_name, $source , $destination , $members[] )
    {

        $users = DB::table('users')->insert(array(
            'user_name' => $user_name,
            'source' => $source,
            'destination' => $destination,
        ));
    }

How Can I store array of members in database as well ?

Thank You in Advance.

Upvotes: 0

Views: 2703

Answers (1)

rchh
rchh

Reputation: 51

You can do something like this:

Route::get('users/{user_name}/{source}/{destination}/{members}' , 'Userscontroller@index')->where(['members'=>'.*']);

Then in your controller...

$members = explode("/", $members);

This would let you use a URL like

/users/user_name/source/destination/member1/member2/member3


For storing arrays in databases whilst using eloquent... I've just realised you're not using a Model here but inserting straight into the database, I'd suggest creating a Users model and then you can do this with the below. Otherwise any request for this data you'll need to remember to manually unserialise in whatever format you serialised the data in.

Using attribute casting inside a model (https://laravel.com/docs/5.2/eloquent-mutators#attribute-casting):

Add to the Model:

protected $casts = ['members'=>'array'];

Then you let Laravel do the rest for you:

 $users = Users::insert(array(
        'user_name' => $user_name,
        'source' => $source,
        'destination' => $destination,
        'members' => $members
    ));

Upvotes: 1

Related Questions