2014-05-21 7 views
0

J'ai 3 tables.Beaucoup de relations Laravel

  1. messages
  2. catégories
  3. category_post.

Je souhaite ajouter category_id et post_id dans ma table category_post lorsque vous créez un post avec des catégories. J'ai une case à cocher pour les catégories.

Le thème principal est, je veux créer un article avec plusieurs catégories. Donc je veux ajouter category_id et post_id dans la table category_post.

est-ce possible avec laravel ???

J'ai vu beaucoup de tutoriel et maintenant je suis fatigué. Aidez-moi, s'il vous plaît.

S'il vous plaît voir le code ci-dessous.

Mes migrations: tables

<?php 
use Illuminate\Database\Migrations\Migration; 
use Illuminate\Database\Schema\Blueprint; 

class CreateCategoriesTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void 
*/ 
public function up() 
{ 
    Schema::create('categories', function(Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->string('category_slug'); 
     $table->timestamps(); 
    }); 
} 


    public function up() 
{ 
    Schema::create('posts', function(Blueprint $table) { 
     $table->increments('id'); 
     $table->string('title'); 
     $table->string('slug'); 
     $table->string('meta'); 
     $table->text('body'); 
     $table->string('image'); 
     $table->timestamps(); 
    }); 
} 
    public function up() 
{ 
    Schema::create('category_post', function(Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('category_id')->unsigned()->index(); 
     $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); 
     $table->integer('post_id')->unsigned()->index(); 
     $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); 
    }); 
} 


/** 
* Reverse the migrations. 
* 
* @return void 
*/ 
public function down() 
{ 
    Schema::drop('categories'); 
} 

    public function down() 
{ 
    Schema::drop('posts'); 
} 

    public function down() 
{ 
    Schema::drop('category_post'); 
} 
    } 

Mon poste Contrôleur:

<?php 

    class PostsController extends \BaseController { 

/** 
* Display a listing of posts 
* 
* @return Response 
*/ 
public function index() 
{ 
    $posts = Post::all(); 

    return View::make('admin.posts.index', compact('posts')); 
} 

/** 
* Show the form for creating a new post 
* 
* @return Response 
*/ 
public function create() 
{ 
    $categories = Category::all(); 


    return View::make('admin.posts.create',compact('categories')); 
} 

/** 
* Store a newly created post in storage. 
* 
* @return Response 
*/ 
public function store() 
{ 
    $validator = Validator::make($data = Input::all(), Post::$rules); 

    if ($validator->fails()) 
    { 
     return Redirect::back()->withErrors($validator)->withInput(); 
    } 

    Post::create($data); 

    return Redirect::route('admin.posts.index'); 
} 

/** 
* Display the specified post. 
* 
* @param int $id 
* @return Response 
*/ 
public function show($id) 
{ 
    $post = Post::findOrFail($id); 

    return View::make('admin.posts.show', compact('post')); 
} 

/** 
* Show the form for editing the specified post. 
* 
* @param int $id 
* @return Response 
*/ 
public function edit($id) 
{ 
    $post = Post::find($id); 

    return View::make('admin.posts.edit', compact('post')); 
} 

/** 
* Update the specified resource in storage. 
* 
* @param int $id 
* @return Response 
*/ 
public function update($id) 
{ 
    $post = Post::findOrFail($id); 

    $validator = Validator::make($data = Input::all(), Post::$rules); 

    if ($validator->fails()) 
    { 
     return Redirect::back()->withErrors($validator)->withInput(); 
    } 

    $post->update($data); 

    return Redirect::route('admin.posts.index'); 
} 

/** 
* Remove the specified resource from storage. 
* 
* @param int $id 
* @return Response 
*/ 
public function destroy($id) 
{ 
    Post::destroy($id); 

    return Redirect::route('admin.posts.index'); 
} 

    } 

modèle Post Mon:

<?php 

    class Post extends \Eloquent { 

// Add your validation rules here 
public static $rules = [ 
    'title'=>'required|min:2', 
    'image'=>'required|image|mimes', 
    'body' =>'required' 
]; 

// Don't forget to fill this array 
protected $fillable = ['title','meta','slug','image','body']; 

public function categories() 
{ 
    return $this->belongsToMany('Category'); 
} 

} 

Ma Catégorie Contrôleur:

<?php 

class CategoriesController extends \BaseController { 

public function __construct() 
{ 
    $this->beforeFilter('csrf',['on'=>'post']); 
} 

/** 
* Display a listing of categories 
* 
* @return Response 
*/ 
public function index() 
{ 
    $categories = Category::all(); 

    return View::make('admin.categories.index', compact('categories')); 
} 

/** 
* Show the form for creating a new category 
* 
* @return Response 
*/ 
public function create() 
{ 
    return View::make('admin.categories.create'); 
} 

/** 
* Store a newly created category in storage. 
* 
* @return Response 
*/ 
public function store() 
{ 
    $validator = Validator::make($data = Input::all(), Category::$rules); 

    if ($validator->fails()) 
    { 
     return Redirect::back()->withErrors($validator)->withInput(); 
    } 

    Category::create($data); 

    return Redirect::route('admin.categories.index'); 
} 

/** 
* Display the specified category. 
* 
* @param int $id 
* @return Response 
*/ 
public function show($id) 
{ 
    $category = Category::findOrFail($id); 

    return View::make('admin.categories.show', compact('category')); 
} 

/** 
* Show the form for editing the specified category. 
* 
* @param int $id 
* @return Response 
*/ 
public function edit($id) 
{ 
    $category = Category::find($id); 

    return View::make('admin.categories.edit', compact('category')); 
} 

/** 
* Update the specified resource in storage. 
* 
* @param int $id 
* @return Response 
*/ 
public function update($id) 
{ 
    $category = Category::findOrFail($id); 

    $validator = Validator::make($data = Input::all(), Category::$rules); 

    if ($validator->fails()) 
    { 
     return Redirect::back()->withErrors($validator)->withInput(); 
    } 

    $category->update($data); 

    return Redirect::route('admin.categories.index'); 
} 

/** 
* Remove the specified resource from storage. 
* 
* @param int $id 
* @return Response 
*/ 
public function destroy($id) 
{ 
    Category::destroy($id); 

    return Redirect::route('admin.categories.index'); 
} 

    } 

Ma Catégorie Modèle:

<?php 

    class Category extends \Eloquent { 
protected $fillable = ['name','category_slug']; 

public static $rules = ['name'=>'required|min:3','category_slug'=>'required|min:3']; 

public function posts() 
{ 
    return $this->belongsToMany('Post'); 
} 
} 

Créer un message Voir Où je:

@extends('admin.layouts.main') 

@section('content') 
<h2>Create Post</h2> 

@if ($errors->has()) 
    <div class="error"> 
     <p>The Following errors have</p> 

     <ul> 
      @foreach ($errors->all() as $error) 
       <li>{{ $error }}</li> 
      @endforeach 
     </ul> 
    </div> 
@endif 

{{ Form::open(array('action' => '[email protected]')) }} 

<p> 
    {{ Form::label('title') }} 
    {{ Form::text('title') }} 
</p> 
<p> 
    {{ Form::label('meta') }} 
    {{ Form::text('meta') }} 
</p> 
<p> 
    {{ Form::label('slug') }} 
    {{ Form::text('slug') }} 
</p> 
<p> 
    {{ Form::label('body') }} 
    {{ Form::text('body') }} 
</p> 
<p> 
    @foreach ($categories as $category) 
     {{ Form::checkbox('category_id', $category->id) }} 
     {{ Form::label($category->name) }} 
    @endforeach 
</p> 
<p> 
    {{ Form::label('image') }} 
    {{ Form::text('image') }} 
</p> 

{{ Form::submit('Crate Post') }} 
{{ Form::close() }} 

@stop 

Mon itinéraire:

<?php 

/* 
|-------------------------------------------------------------------------- 
| Application Routes 
|-------------------------------------------------------------------------- 
| 
| Here is where you can register all of the routes for an application. 
| It's a breeze. Simply tell Laravel the URIs it should respond to 
| and give it the Closure to execute when that URI is requested. 
| 
*/ 

Route::get('/', function() 
{ 
return View::make('hello'); 
}); 

Route::resource('admin/categories', 'CategoriesController'); 

Route::resource('admin/posts', 'PostsController'); 

S'il vous plaît aidez-moi. Comment ajouter category_id et post_id dans la table categoy_post ????????

Répondre

2

Tout d'abord vous avez besoin d'un tableau des ids de catégories:

// view 
@foreach ($categories as $category) 
    {{ Form::checkbox('categories[]', $category->id, $post->categories->contains($category->id)) }} 
    {{ Form::label($category->name) }} 
@endforeach 

Si vous utilisez modèle de liaison lors de l'édition, puis renommer categories[] à autre chose pour éviter les conflits de nom du champ

Ensuite, vous devez pour synchroniser le message avec les catégories:

// posts controller @store 

... // validate everything, categories too 

$categories = Input::get('categories'); 

$post = Post::create($data); 

$post->categories()->sync($categories); 

return Redirect::route('admin.posts.index'); 
+0

Merci @deczo Ça marche .. Beaucoup de mercis – saiful408

+0

Marquer comme réponse correcte, si cela est fait pour que les autres utilisateurs le sachent. –

+0

Bonjour deczo, maintenant je peux créer des messages. Mais quand j'essaye d'éditer ce post, alors les catégories ne sont pas vérifiées. Mais c'est nécessaire. Comment définir la valeur de la catégorie de case à cocher à partir du tableau croisé dynamique? Cela signifie que je veux montrer les catégories que j'ai sélectionnées en post. Aidez-moi, s'il vous plaît. – saiful408

Questions connexes