Controller con relaciones polimorficas
Publicado por Jaime (1 intervención) el 07/05/2020 13:13:58
Hola, encuentro un problema a la hora de realizar el CRUD cuaNo me queda claro la manera de actuar. A continuación pueden observar una imagen con un esquema de las relaciones entre tablas.
Mi problema es como haría el ImageController, CommentController... de los Modelos con relaciones polimorficas. a continuación adjunto una serie de Modelos:
-User.php
-Post.php
-Image.php
-Comment.php
-Tag.php
Según esto ya he realizo controller del post, PostController.php
Como sería el Controller de Image, Comments y Tag??
Gracias
Mi problema es como haría el ImageController, CommentController... de los Modelos con relaciones polimorficas. a continuación adjunto una serie de Modelos:
-User.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace App;
use App\Profile;
use App\User;
use Caffeinated\Shinobi\Contracts\Role;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
//HasRolesAndPermissions, shinobi
use Caffeinated\Shinobi\Concerns\HasRolesAndPermissions;
class User extends Authenticatable
{
//HasRolesAndPermissions, shinobi
use HasRolesAndPermissions;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//Asi un usuario tendra un perfil
public function profile()
{
return $this->hasOne(Profile::class);
}
//Asi tengo una localizacion a traves de profile, ne cesita un metodo en modelo Profile.php
public function location()
{
return $this->hasOneThrough(Location::class, Profile::class);
}
//un usuario tiene muchos posts
public function posts()
{
return $this->hasMany(Post::class);
}
//un usuario tiene muchos videos
public function videos()
{
return $this->hasMany(Post::class);
}
//un usuario tiene muchos fotos
public function fotos()
{
return $this->hasMany(Post::class);
}
//un usuario tiene muchos comentarios
public function comments()
{
return $this->hasMany(Comment::class);
}
//un usuario tiene una imagen
public function image()
{
return $this->morphOne(Image::class, 'imageable');
}
}
-Post.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
namespace App;
use App\Profile;
use App\User;
use App\Post;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//indico campos que puedo editar
protected $fillable = [
'name', 'category_id'
];
//un post pertenece a un usuario
public function user()
{
return $this->belongsTo(User::class);
}
//un post pertenece a un categoria
public function category()
{
return $this->belongsTo(Category::class);
}
//un post tiene muchos comentarios
public function comments()
{
//especie de hasMany pero polimorfico
return $this->morphMany(Comment::class, 'commentable');
}
//un post tiene una imagen
public function image()
{
//polimorfismo a uno
return $this->morphOne(Image::class, 'imageable');
}
//un post puede tener muchas etiquetas
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}
-Image.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
//indico campos que puedo editar
protected $fillable = [
'url',
];
//
public function imageable()
{ //transformar a pero no especificamos a que
return $this->morphTo();
}
}
-Comment.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{ //transformar a pero no especificamos a que
return $this->morphTo();
}
//un comentario pertenece a un usuario
public function user()
{
return $this->belongsTo(User::class);
}
}
-Tag.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
//una etiqueta tiene muchos posts
public function posts()
{
return $this->morphedByMany(Post::class, 'taggable');
}
//un video tiene muchos posts
public function videos()
{
return $this->morphedByMany(Video::class, 'taggable');
}
//un video tiene muchos posts
public function fotos()
{
return $this->morphedByMany(Foto::class, 'taggable');
}
}
Según esto ya he realizo controller del post, PostController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<?php
namespace App\Http\Controllers;
use App\Post;
use App\User;
use App\Location;
use App\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::paginate();
return view('posts.index', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//validacion
$this->validate($request, ['name'=>'required', ]);
$post = new Post;
$post->category_id=$request->category_id;
$post->user_id=Auth::user()->id;
$post->name=$request->name;
$post->save();
return redirect()->route('posts.show', $post->id)->with('info', 'Post creado con exito');
}
/**
* Display the specified resource.
*
* @param \App\Post $post
* @return \Illuminate\Http\Response
*/
public function show(Post $post)
{
//
return view('posts.show', compact('post'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Post $post
* @return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
//
$user= Auth::user();
if ($user->id==$post->user_id) {
return view('posts.edit', compact('post'));
}
else{
return redirect()->route('home')->with('info', 'Solo puedes editar o borrar tus posts');
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Post $post
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$post->update($request->all());
return redirect()->route('posts.show', $post->id)->with('info', 'Post actualizado con exito');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Post $post
* @return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
//
$user= Auth::user();
$post=$user->post;
$post->delete();
return redirect()->route('home')->with('info', 'Post borrado con exito');
}
}
Gracias
Valora esta pregunta
0