How to display related tables in Laravel 5? - php

I've got two different tables, one is called articles, the other one images I Want to create an article that contains multiple images,
How can I create with Laravel 5.5 a many-to-many relation? I've followed this post on laracast: https://laracasts.com/discuss/channels/laravel/multiple-images-in-article-galerry
here is the code
ARTICLE MODEL
public function images() {
return $this->belongsToMany('App\Image');
}
IMAGE MODEL
public function articles() {
return $this->belongsToMany('App\Article');
}
ARTICLE-IMAGE MIGRATION(TABLE)
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleImageTable extends Migration {
public function up()
{
Schema::create('article_image', function(Blueprint $table)
{
$table->increments('id');
$table->integer('article_id')->unsigned()->index();
$table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
$table->integer('image_id')->unsigned()->index();
$table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop('article_image');
}
}
ARTICLES CONTROLLER
<?php namespace App\Http\Controllers;
use App\Article;
class ArticlesController extends Controller
{
public function index()
{
$articles = Article::with('images')->get();
return view('articles.index', compact('articles'));
}
public function show($id)
{
$article = Article::find($id);
$article->load('images');
return view('articles.show', compact('article'));
}
}
MY PROBLEM IS How do i continue from here(that is display both the articles and the images)

Related

Laravel Model relationship "Page have many Attachments"

I have models:
Page:
id
slug
Image
id
file
Video
id
file
I need the Page model to have a relation with several Image and Video models through one relationship, like
foreach($page->attachments as $attachment)
{
// $attachment can be Image or Video
}
And inserts like
$attachments = [$image, $video];
$page->attachments()->saveMany($attachments);
I tried to make a morph relationship, but nothing comes of it, please help.
Create an Attachment Model and attachments Table with the following columns/properties:
id
file
page_id
type (video/image)
then you could add hasmany relationship to your page model
public function attachments()
{
return $this->hasMany(Attachment::class);
}
Then you can fetch the attachment like you tried
In order to achieve this you have to make table for relations. This table should be defined like this:
page_image_video
id
page_id
image_id
video_id
And fields page_id, image_id and video_id should be a foreign keys. This is a table where you will save you attachments for your page. After that, you can define method attachments() in you Page Model with hasMany().
Create Migration :
Page Table :
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("slug");
$table->timestamps();
});
Image Table :
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string("file");
$table->timestamps();
});
Videos Table :
Schema::create('video', function (Blueprint $table) {
$table->increments('id');
$table->string("file");
$table->timestamps();
});
Pageables Table :
Schema::create('pageables', function (Blueprint $table) {
$table->integer("pages_id");
$table->integer("pageable_id");
$table->string("pageable_type");
});
Create Model :
Now, we will create Pages, Images and Video model. we will also use morphToMany() and morphedByMany() for relationship of both model.
Video Model :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
use HasFactory;
protected $table='video';
protected $primaryKey='id';
protected $guarded = [];
public function pages()
{
return $this->morphToMany(Pages::class, 'pageable');
}
}
Images Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Images extends Model
{
use HasFactory;
protected $table='image';
protected $primaryKey='id';
protected $guarded = [];
public $timestamps = false;
public function pages()
{
return $this->morphToMany(Pages::class, 'pageable');
}
}
Pages Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
class Pages extends Model
{
use HasFactory;
protected $table='page';
protected $primaryKey='id';
protected $guarded = [];
public $timestamps = false;
public function posts()
{
return $this->morphedByMany(Images::class, 'pageable');
}
/**
* Get all of the videos that are assigned this tag.
*/
public function videos()
{
return $this->morphedByMany(Video::class, 'pageable');
}
}
Retrieve Records :
$pages = Pages::find(1);
foreach ($pages->posts as $post) {
var_dump($post);
}
foreach ($pages->videos as $video) {
print_r('<br>');
//var_dump($video);
}
Create Records :
$page = Pages::find(1);
$img = new Images();
$img->file = "test insert";
$page->posts()->save($img);
All done.

Laravel 7 One To Many Relations?

Below are all of the models, migrations and controller.
Donation Model
class Donation extends Model
{
protected $guarded =[];
public function users(){
return $this->hasMany(User::class);
}
public function items(){
return $this->belongsTo(DonationItems::class);
}
}
Donation Items Model:
class DonationItems extends Model
{
protected $guarded=[];
public function donation(){
return $this->hasMany(Donaition::class);
}
}
Donation Items Migration:
public function up()
{
Schema::create('donation_items', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->timestamps();
});
}
Donation Migration:
public function up()
{
Schema::create('donations', function (Blueprint $table) {
$table->id();
$table->string('item');
$table->unsignedInteger('user_id');
$table->unsignedInteger('donation_item_id');
$table->timestamps();
});
}
In my controller I want to access the items as follows:
$don = Donation::all();
$don->items;
But I'm unable to achieve this.
Its not working because laravel follows one rule for relationships:
Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.
So you can try by supplying local and foreign id
So it would look something like this
Donation Model
class Donation extends Model
{
protected $guarded =[];
public function users(){
return $this->hasMany(User::class);
}
public function items(){
return $this->belongsTo(DonationItems::class, 'donation_item_id', 'id');
}
}
Donation Items Model:
class DonationItems extends Model
{
protected $guarded=[];
public function donation(){
return $this->hasMany(DonationItems::class, 'id', 'donation_item_id');
}
}
I am writing from my head you might need to swap local and foreign ID's

i want to return the projects of specific user?

I want to return the projects of the authenticated user, but am not getting any. I know the records exist in the database.
This is my model Project:
public function users(){
return $this->hasMany(User::class);
}
this is my model User:
public function projects(){
return $this->hasMany(Projet::class,'user_id');
}
and this is the controller function :
public function projetuser(){
$user = User::find(auth()->user()->id);
return $user->projects;
}
and this my user_projet migration:
public function up()
{
Schema::create('user_projet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('projet_id');
$table->foreign('projet_id')->references('id')->on('projets')->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('membre')->nullbale();
$table->timestamps();
});
}
You are defining a many-to-many relationship incorrectly. Use belongsToMany() instead of hasMany(). Because your pivot table name is not standard (it should be alphabetic order projet_user) you need to include it in the relationship definition as well.
<?php
use Illuminate\Database\Eloquent\Model;
class Projet extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'user_projet');
}
}
class User extends Model
{
public function projets(){
return $this->belongsToMany(Projet::class, 'user_projet');
}
}
Now in your controller you can do this:
public function projetuser(){
return auth()->user->projets;
}
Your question seems to vary between "projet" and "project." I assumed "projet" was the correct spelling, but try to keep this consistent.
Please note also the typo in your migration: nullbale.

Is there an easier way to code laravel eloquent models besides what I have here?

I created this code to work with laravel 5.8 to access a database with many foreign keys, seems like I am subverting the foreign keys, am I missing something, was hoping someone could point me in the right direction.
It works, but I think I am overdoing it and missing some eloquent shortcuts.
namespace App\Models\Entities;
use Illuminate\Database\Eloquent\Model;
class AbstractModel extends Model
{
public function isDuplicate(Model $model) {
return $model::where($model->getAttributes())->first();
}
}
///
namespace App\Models\Entities;
abstract class AbstractForeignModel extends AbstractModel {
public $timestamps = false;
public $fillable = ['value'];
public function store($value){
$foreign = $this->newInstance();
$foreign->value = $value;
if(!$this->isDuplicate($foreign)){
$foreign->save();
}
return $foreign->getId($value);
}
public function setValueAttribute($value){
$this->attributes['value'] = $value;
}
public function getId($value){
$result = self::where('value', $value)->first();
if($result){
return $result->id;
}
}
public function getValue($id){
$result = self::where('id', $id)->first();
if($result){
return $result->value;
}
}
}
///
namespace App\Models\Entities\Video;
use App\Models\Entities\AbstractForeignModel;
class ForeignModel extends AbstractForeignModel {
public function video() {
return $this->belongsTo('App\Models\Entities\Video');
}
}
Author, Description, Source, Title extend the above as empty classes
use App\Models\Entities\Video\Author;
use App\Models\Entities\Video\Description;
use App\Models\Entities\Video\Source;
use App\Models\Entities\Video\Title;
use Carbon\Carbon;
class Video extends AbstractModel {
protected $fillable = ['author_id', 'title_id', 'description_id',
'source_id', 'published_at'];
public function store($data) {
$video = new Video;
$video->author_id = $data->author;
$video->title_id = $data->title;
$video->description_id = $data->description;
$video->source_id = $data->source;
$video->published_at = $data->published_at;
if (!$this->isDuplicate($video)) {
$video->save();
}
}
public function setPublishedAtAttribute($value){
$this->attributes['published_at'] = Carbon::parse($value)->toDateTimeString();
}
public function setTitleIdAttribute($value) {
$this->attributes['title_id'] = (new Title)->store($value);
}
public function setDescriptionIdAttribute($value) {
$description = (new Description)->store($value);
$this->attributes['description_id'] = $description;
}
public function setSourceIdAttribute($value) {
$this->attributes['source_id'] =(new Source)->store($value);
}
public function setAuthorIdAttribute($value) {
$this->attributes['author_id'] = (new Author)->store($value);
}
public function getAuthorIdAttribute($value) {
$this->attributes['author_id'] = (new Author)->getValue($value);
}
public function getTitleIdAttribute($value) {
$this->attributes['title_id'] = (new Title)->getValue($value);
}
public function getDescriptionAttribute($value) {
$this->attributes['description_id'] = (new Description)->getValue($value);
}
public function getSourceIdAttribute($value) {
$this->attributes['source_id'] = (new Source)->getValue($value);
}
public function author() {
return $this->belongsTo('App\Models\Entities\Video\Author', 'author_id');
}
public function description() {
return $this->belongsTo('App\Models\Entities\Video\Description', 'description_id');
}
public function title() {
return $this->belongsTo('App\Models\Entities\Video\Title', 'title_id');
}
public function source() {
return $this->belongsTo('App\Models\Entities\Video\Source', 'source_id');
}
}
video migration file
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration {
public function up() {
Schema::create('videos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('source_id');
$table->unsignedBigInteger('title_id');
$table->unsignedBigInteger('description_id');
$table->unsignedBigInteger('author_id');
$table->dateTimeTz('published_at');
$table->timestamps();
$table->foreign('source_id')->references('id')->on('sources');
$table->foreign('title_id')->references('id')->on('titles');
$table->foreign('description_id')->references('id')->on('descriptions');
$table->foreign('author_id')->references('id')->on('authors');
});
}
public function down() {
Schema::dropIfExists('videos');
}
}
The foreign key migration files follow this layout for Author, Description, Source, Title
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTitlesTable extends Migration
{
public $timestamps = false;
public function up()
{
Schema::create('titles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('value');
});
}
public function down()
{
Schema::dropIfExists('titles');
}
}
could probably create a foreign migration class and just set the variables that I need
What you're probably looking for is firstOrCreate
There are two other methods you may use to create models by mass
assigning attributes: firstOrCreate and firstOrNew. The firstOrCreate
method will attempt to locate a database record using the given column
/ value pairs. If the model can not be found in the database, a record
will be inserted with the attributes from the first parameter, along
with those in the optional second parameter.
The firstOrNew method, like firstOrCreate will attempt to locate a
record in the database matching the given attributes. However, if a
model is not found, a new model instance will be returned. Note that
the model returned by firstOrNew has not yet been persisted to the
database. You will need to call save manually to persist it.

Laravel 4.2 and migrate make not working

I create a project based on the book Getting Started with Laravel 4.
So, I create two files in app/models/ - Cat.php and Breed.php with this content:
Cat.php
<?php
class Cat extends Eloquent {
protected $fillable = array('name','date_of_birth','breed_id');
public function breed() {
return $this->belongsTo('Breed');
}
}
and Breed.php
<?php
class Breed extends Eloquent {
public $timestamps = false;
public function cats()
{
return $this->hasMany('Cat');
}
}
and after, I use command php artisan migration:make create_cats_and_breeds_table
Ok, and should arise file in app/database/migrations. It is.
But, its contents it's not same as in the book...
In book:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddCatsAndBreedsTable extends Migration {
public function up()
{
Schema::create('cats', function($table)
{
$table->increments('id');
$table->string('name');
$table->date('date_of_birth');
$table->integer('breed_id')->nullable();
$table->timestamps();
})
Schema::create('breeds', function($table)
{
$table->increments('id');
$table->string('name');
})
}
public function down()
{
Schema::drop('cats');
Schema::drop('breeds');
}
}
My code:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddCatsAndBreedsTable extends Migration {
public function up()
{
//
}
public function down()
{
//
}
}
What's happen?
https://github.com/laracasts/Laravel-4-Generators
Provides some additional artisan commands which you can used to specific your fields in order to generate the migration files.
php artisan generate:migration create_posts_table --fields="title:string, body:text"
migration:make command does not know anything about your models. It just creates a stub that you need to fill with column definitions for your tables.

Categories