jeudi 3 décembre 2015

How to insert data using relation in laravel 5?

I have two table

ImagePortfolio

id|id_portfolio|image

Portfolio

id|title|year|description

Relation

class Portfolio extends Model
{
    protected $table = 'portfolio';

    protected $fillable = ['id','title','year','description'];

    public function imageportfolio(){ 
        return $this->hasMany('App\ImagePortfolio','id_portfolio','id'); 
    }

    public static $portfolio = array(
            'title' =>  'required',
            'year' =>  'required',
            'description' =>  'required',
            );      
}

class ImagePortfolio extends Model
{
    protected $table = 'imageportfolio';

    protected $fillable = ['id','id_portfolio','image'];

    public function portfolio() {
        return $this->belongsTo('App\Portfolio', 'id', 'id_portfolio');
    }

    public static $imageportfolio= array(
            'image' => 'image|max:3000|mimes:jpeg,jpg,png'
            );      
}

Controller

public function InsertPortfolio() { 
    $portfolio = Input::except('_token'); 
    $portfolio['id'] = Input::get('id');
    $request['id_portfolio'] = Input::get('id');
    $validation = Validator::make($portfolio, Portfolio::$portfolio); 
    if ($validation->passes()) {
        if($user = Portfolio::find($portfolio['id'])) {
            $user -> update($portfolio); 
            Session::flash('editportfolio', 'Success'); 
            return Redirect::to('backend/portfolio');                   
        }else{
                $file = array_get($portfolio,'image');
                $destinationPath = 'image/profile/';
                $extension =  $request->file('image')->getClientOriginalExtension();
                $fileName = rand(1111,9999) . '.' . $extension;
                Image::make($file)->resize(400, 400)->save($destinationPath.$fileName);
            $user = Portfolio::insert($portfolio);                  
            }
            Session::flash('portfolio', 'Success'); 
            return Redirect::to('backend/portfolio');
        } else { 
            return Redirect::to('backend/portfolio/editar/'.$portfolio['id'])->withInput()->withErrors($validation); 
        }   
    }

I can not enter without the image table but I need to enter the two. I have one form where i adding post title ,post content and selecting multiple images. My question is how I can store post images along with post id in post_images table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire