Laravel Category Model Relationships - laravel

I have the following table structure in my database.
Table Name: tiles
Columns: id, tile_name, tile_thumb, tile_snippet
Table Name: tags
Columns: id, tag_title
Table Name: tile_tags
Columns: id, tile_id, tag_id
Models:
Tile, Tag, TileTag
In my main model class for entries I am specifying the following relationship to a model called TileTag which is a pivot table.
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsTo('Tiles\TileTag');
}
}
During my foreach loop it returns the tile_name and any other columns from my table, except the ones joined by the relatipnship.
#foreach($tiles as $tile)
<a href="tile/{{$tile->tile_name}}">
<li class="col-md-4 mix" data-category="{{ $tile->tags->tag_title }}">
{!! HTML::image($tile->tile_thumb, null, array('class' => 'img-responsive')) !!}
</li>
</a>
#endforeach
How can I get my categories/tags linked to my primary entries when they are sorted during each loop?
I try returning the data during the loop by {{ $tile->tags->tag_title }} but it returns an empty string.
Controller Method:
class TileController extends Controller {
/**
* Display a listing of tiles from the database.
*
* #return Response
*/
public function index() {
// Get tile data from the model
$tiles = \Tiles\Tile::all();
return view('pages.index', compact('tiles'));
}
Returned Array:

I think that you don't have to create a model for Tile_Tag. Laravel can handle ManyToMany relationships out of the box (I suppose that this is the type of the relationship because you use pivot table). Your models should be
class Tile extends Model {
protected $table = 'tiles';
public function tags() {
return $this->belongsToMany('Tiles\Tag');
}
}
and
class Tag extends Model {
protected $table = 'tags';
public function tiles() {
return $this->belongsToMany('Tiles\Tile');
}
}
Laravel will know that you have a pivot table named "tag_tile" with columns "tag_id" and "tile_id". Check the relevant documentation here
Then you can iterate through tags collection for each tile like this
#foreach ($tiles as $tile)
{!!$tile->tile_name!!}
#foreach ($tile->tag as $tag)
{!!$tag->tag_title!!}
#endforeach
#endforeach
Hope it helps.

Related

Trying to get property 'name' of non-object?

Hi Guys i am new to laravel and i am trying to retrieve category names for each formation and i am getting this error
Trying to get property 'name' of non-object (0)
The "name" i am trying to retrieve is the name of category that my formation belongs to.
This is My Category Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
function formations()
{
return $this->hasMany('App\Formation');
}
protected $fillable =['name','description'];
}
And This is My Formation Model
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"category_id");
}
protected $fillable =['name','price','durations','category_id'];
}
And here is my view page where i am trying to retrieve the category name
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
td>{{$formation->durations}}</td>
#endforeach
This is My Controller
public function index()
{
//$formations = Formation::all();
$formations = Formation::with('category')->paginate('4');
$categories = Category::all();
return view('formation.index',compact('categories','formations'));
}
Any Suggestion about where i might be wrong ? And thanks in Advance !
This error usually comes when you have removed one or more row from database, but trying to access that row with an id. Make sure that you have all the category in the category table with the id which is mentioned in the formation table category_id field.
In your view
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td> {{ $formation->categories()->pluck('name')->implode(' ') }}</td>
<td>{{$formation->durations}}</td>
#endforeach
Try changing the relationship
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"id","category_id"); //if your categories id is id
}
protected $fillable =['name','price','durations','category_id'];
}
In your view
#foreach($formations as $formation)
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
<td>{{$formation->durations}}</td>
#endforeach
The Problem was that i have deleted a row from my category table in database that's why the name wasn't recognized.

Laravel - hasMany() and belongsTo() not working correctly for me in #foreach loop

I got following error when I try to use this on my page
Trying to get property of non-object
I have two tables:
cvicenis
id
title
body
category_id
categories
id
name
My Cviceni model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cviceni extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'id');
}
}
My Category model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function cviceni()
{
return $this->hasMany('App\Cviceni', 'category_id');
}
}
My controller:
public function index()
{
$cviceni = Cviceni::all();
return view('excercises.index', compact('cviceni'));
}
My index.blade:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-3">
<h1>Přehled cvičení</h1>
#if(count($cviceni) > 0)
<ul>
#foreach ($cviceni as $c)
<li> {{ $c->category->name }}</li>
#endforeach
</ul>
#else
<h2>There is nothing to display</h2>
#endif
</div><!-- end of column -->
</div><!-- end of row -->
#endsection
If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?
In the Cviceni model, I think you set up the foreign key is wrong. Your foreign key in the table is category_id, while you set up the relationship with foreign key is id. Try to replace the category() relationship with follow
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
You need to eager load the models if you need them:
public function index()
{
$cviceni = Cviceni::with("category")->get();
return view('excercises.index', compact('cviceni'));
}

How can I display value of pivot table ? Laravel 5.3

I have 3 model : store model, product model, order model
store model is like this :
class Store extends Model
{
protected $fillable = ['name', 'user', 'address', 'phones', 'email', 'photo'];
...
}
product model is like this :
class Product extends Model
{
protected $fillable = ['store_id','category_id','name', 'photo','description'];
...
}
order model is liket this :
class Order extends Model
{
...
public function products()
{
return $this->belongsToMany(Product::class, 'orders_products')
->withPivot('sub_total','quantity','price','information')->withTimestamps();
}
public function store()
{
return $this->belongsTo(Store::class);
}
}
I have 4 table : stores table, orders table, products table, orders_products table
orders_producs table is pivot table
In view blade laravel I call this :
{{ $order->store->name }}
It works. It success display store name
My problem is when I want to display product name
In view blade laravel I try :
{{ $order->products->name }}
There exist error :
Undefined property: Illuminate\Database\Eloquent\Collection::$id
(View:...
It seems the wrong way of calling
How can I solve it?
Since it's belongsToMany(), you can display data like this:
#foreach ($order->products as $product)
{{ $product->name }}
{{ $product->pivot->price }}
#endforeach

Laravel : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails - Many to Many relationship

I know there's a bunch of problems asked about laravel integrity constraint violation, but none of them are Many to Many relationship, which is my case. Basically I have a table Hobi (hobby) and table Siswa (student), and the relationship is many to many since a student can have many hobbies and a hobby can be favored by many students. So here is the code :
This is my model Hobi :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Hobi extends Model
{
protected $table = 'hobi';
protected $fillable = [
'nama_hobi',
];
public function siswa(){
return $this->belongsToMany('App\Siswa', 'hobi_siswa', 'id_hobi', 'id_siswa');
}
}
model Siswa :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Siswa extends Model
{
protected $table = 'siswa';
protected $fillable = [
'nisn',
'nama_siswa',
'tgl_lahir',
'jns_klmin',
'id_kelas',
'id_hobi',
];
public function hobi(){
return $this->belongsToMany('App\Hobi', 'hobi_siswa', 'id_siswa', 'id_hobi')->withTimeStamps();
}
}
A piece of form view code which contained Hobi :
#if($errors->any())
<div class="form-group {{$errors->has('hobi') ? 'has-error' : 'has-success'}}">
#else
<div class="form-group">
#endif
{!! Form::label('hobi', 'Hobi:', ['class'=>'control-label']) !!}
#if(count($hobi_list) > 0)
#foreach($hobi_list as $key => $value)
<div class="checkbox">
<label>{!! Form::checkbox('hobi[]', $value, null) !!}{{$value}}</label>
</div>
#endforeach
#else
<p>Tidak ada pilihan hobi.</p>
#endif
</div>
And finally the controller :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Siswa;
use App\Telepon;
use App\Kelas;
use App\Hobi;
use Validator;
class SiswaCont extends Controller
{
public function siswa(){
$siswa_list = Siswa::orderBy('nama_siswa', 'asc')->paginate(10);
$jmlh_siswa = Siswa::count();
return view('siswa.ssw', compact('siswa_list', 'jmlh_siswa'));
}
public function create(){
$kelas_list = Kelas::lists('nama_kelas', 'id');
$hobi_list = Hobi::lists('nama_hobi', 'id');
return view('siswa.create', compact('kelas_list', 'hobi_list'));
}
public function store(Request $request){
$input = $request->all();
$validator = Validator::make($input, [
'nisn'=>'required|string|size:4|unique:siswa,nisn',
'nama_siswa'=>'required|string|max:30',
'tgl_lahir'=>'required|date',
'jns_klmin'=>'required|in:L,P',
no_telepon'=>'sometimes|numeric|digits_between:10,15|unique:telepon,no_telepon',
'id_kelas'=>'required',
]);
if ($validator->fails()) {
return redirect('siswa/create')->withInput()- >withErrors($validator);
}
$siswa = Siswa::create($input);
$siswa->hobi()->attach($request->input('hobi'));
return redirect('siswa');
}
}
I'm using pivot table hobi_siswa to contain id_siswa and id_hobi, creating a bridge. Hobi itself in form view is checkbox modeled. The problem is constraint, data Siswa for another column (nisn, nama_siswa, telepon, etc.) are saved, but Hobi not. Any help appreciated.
Use sync method instead of attach which accepts an array.
From the Docs
The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table.
For example:
$user->roles()->sync([1, 2, 3]);

Access user's properties (with pivot table) laravel 5.1

I have a users table. The user has possibility to upload a post. The post is saved well to the database. The users can follow each other - so on a pivot table each follower_id has followees_id.
I need to get the posts of the current user followee's . I am kinda messed with getting it from a pivot table.
Here's my code so far:
controller:
protected function get_followee_posts($followee_posts) ////$followee_posts passed from the route.
{
$user = $this->user;
$user->followee()->attach($followee_posts);
$followee_posts = User::find($followee_posts);
}
view:
<div class="following_posts">
<p> Posts from people you're following: <p>
#foreach ($user->follower_id->followee_id->posts as $post)
<form action="/html/tags/html_form_tag_action.cfm" method="post">
<textarea name="comments" id="comments" style="width:96%;height:90px;background-color:white;color:black;border:none;padding:2%;font:22px/30px sans-serif;">
{!! $posts->full_post !!} </textarea>
</form>
#endforeach
route:
Route::get('hub/{followee_posts}','HubController#get_followee_posts')->name('followee_posts');
I am getting an error with the current code saying:
ErrorException in 7340f90cc5faf1a298fcc646b7248b22 line 105:
Trying to get property of non-object
Any help would be lovely. Thank you.
Your not too specific about your schema, but this is how I would go about it.
User Model
class User extends Model
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
}
Follower Model
class Follower extends Model
{
protected $table = 'followers';
public function user()
{
return $this->belongs_to('User');
}
public function posts()
{
return $this->hasMany('Post', 'user_id', 'follower_id');
}
}
Post Model
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongs_to('User');
}
}
The followers table would look something like this:
user_id
follower_id
You could then use eloquent method chains to get the posts of a users followers:
// Get Users object with followers and followers posts
// We use with() to eager load relationships
$user = User::with('followers.posts')->find(2);
// Return associative array of post objects
$postsArray = $user->followers->lists('posts');
// Combine posts into a single collection
$posts = (new \Illuminate\Support\Collection($postsArray))->collapse()->toArray();
print_r($posts);

Resources