简体   繁体   中英

Array to string conversion laravel

In my blade view I have inputs like this:

<input type="time" class="" name="shipping_hours[saturday][from]" value="" />
<input type="time" class="" name="shipping_hours[saturday][to]" value="" />
<input type="checkbox" name="shipping_hours[saturday][all_day]" /> <label class="">24h</label>

And I have a table, shipping_hours in a mysql database. I want save data in this JSON format:

{"monday":{"from":"13:00","to":"22:00"},"tuesday":{"from":"13:00","to":"22:00"},"wednesday":{"from":"13:00","to":"22:00"},"thursday":{"from":"13:00","to":"22:00"},"friday":{"from":"13:00","to":"01:00"},"saturday":{"from":"13:00","to":"01:00"},"sunday":{"from":"12:00","to":"22:00"}}

How I can do this in laravel?

Controller (store funtion)

public function store(Request $request)
{
    $data = $this->validator($request->all())->validate();
    settings_hours::create($data);
    session()->flash('message_success', "Object added");
    return redirect(route('hours'));        
}

Controller (validator function)

protected function validator($data) {
    return Validator::make($data, [
        'place_id' => 'required',
        'opening_hours.*' => 'nullable',
        'kitchen_hours.*' => 'nullable',
        'shipping_hours.*' => 'nullable',
        'breakfast_hours.*' => 'nullable',
        'launch_hours.*' => 'nullable',
        'reservation_hours.*' => 'nullable'
    ]);
}  

Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class settings_hours extends Model
{
    public $timestamps = false;

    protected $fillable = [
        'place_id',
        'opening_hours',
        'kitchen_hours',
        'shipping_hours',
        'breakfast_hours',
        'launch_hours',
        'reservation_hours'
    ];
}
$string='hello,min,max';    
implode(',',$array);

In model im added this code and is worked, i think is be helpful

    protected $casts = [
    'place_id' => 'integer',
    'opening_hours' => 'array',
    'kitchen_hours' => 'array',
    'shipping_hours' => 'array',
    'breakfast_hours' => 'array',
    'launch_hours' => 'array',
    'reservation_hours' => 'array'
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM