relation data does not appear in the laravel view - php

relation data does not appear in the laravel view
> View
<td>
#foreach($p->jenis as $a)
{{ $a->jenis_penyedia }},
#endforeach
</td>
coba
> Model Jenis.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Jenis extends Model
{
protected $table="tbl_jenis_penyedia";
protected $fillable=['id_jenis_penyedia','jenis_penyedia'];
public function profile(){
return $this->belongsTo('App\Profile');
}
}
> Model Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table="tbl_profil_penyedia";
protected $fillable=['id_profil_penyedia','id_jenis_penyedia','nama', 'no_ktp', 'file', 'npwp', 'bank', 'no_rek', 'email', 'no_telp', 'keahlian', 'pengalaman', 'alamat', 'pendidikan'];
public function jenis(){
return $this->hasMany('App\Jenis');
}
}
Model
> Controller
$profile = Profile::all();
return view('profile/homeprofile',['profile' => $profile]);
Controller
no error
only data does not appear

Check your db migration file. define this in create_tbl_profil_penyedia_table :
Migrate it.
$table->unsignedInteger('id_jenis_penyedia')->unsigned();
$table->foreign('id_jenis_penyedia')->references('id_jenis_penyedia')->on('tbl_jenis_penyedia');
Edit your Jenis model
public function jenis(){
return $this->hasMany('App\Jenis', 'id_jenis_penyedia');
}
According to your controller your view should work like this:
#foreach($profile as $p)
#foreach($p as $a)
{{ $a->jenis->jenis_penyedia }},
#endforeach
#endforeach

Related

Undefined property: App\Models\Product::$category Laravel 8

I am creating a simple inventory system using Laravel 8.
I want to join two tables: category and products
Category table:
id
categoryname
1
drink
2
biscuits
3
toy
Products table:
id
prodname
catid
1
fanta
1
2
apple juice
1
3
buildblocks
3
I need the data passed to the table as the below output
id
productname
categoryname
1
fanta
drink
While running the program I got the error as:
Undefined property: App\Models\Product::$category
Category
class Category extends Model
{
protected $fillable = [
'id',
'catname',
];
public function products()
{
return $this->hasMany('App\Models\Product', 'id', 'catid');
}
}
Products
class Product extends Model
{
protected $fillable = [
'id',
'prodname',
'catid',
];
public function category()
{
return $this->belongsTo('App\Models\Category', 'category', 'id');
}
}
view.blade.php
<html>
<head>
<body>
<tbody>
#foreach ($products as $key => $product)
<tr>
<td>{{ $key }}</td>
<td>{{ $product->prodname }}</td>
<td>{{ $product->category->catname }}</td>
</tr>
#endforeach
</tbody>
</body>
</head>
</html>
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function view()
{
$products = Product::with('category')->get();
$categories = Category::with('product')->get();
return view('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
}
Routes
Route::get('/products', [ProductController::class, 'view']);
You are mistaken in model here is an example
change catid to category_id
your colum in product table should be category_id in databsse to
In My user table
public function employee()
{
return $this->hasOne(Employee::class, 'user_id', 'id');
}
Here is my employee table
public function user()
{
return $this->belongsTo(User::class);
}
You have to work on you controller methods look here
public function showEmployee()
{
$emps = User::with('employee');
return view('employee.show_emp', compact('emps'));
}
Routes like this
Route::resource('showEmployee','EmpController#showEmployee');
Here is an Your solution I am Trying to put my comfort.
Category
use App\Models\Product;
class Category extends Model
{
protected $fillable = [
'id',
'catname',
];
public function products()
{
return $this->hasMany(Product::class, 'catid', 'id');
}
}
Products
use App\Models\Category;
class Product extends Model
{
protected $fillable = [
'id',
'prodname',
'catid',
];
public function category()
{
return $this->belongsTo(Category::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function view()
{
$products = Product::with('category')->get();
$categories = Category::with('product')->get();
return view('employee.show_emp', compact('products', 'categories'));
}
}
Routes
Route::get('products','ProductController#view');
Add these both lines to your both models after namspace one of each
For Category
use App\Models\Product;
For Product
use App\Models\Category;
Note: this is untested code
Here i try to solve your problem
The foreign key passed to the relationship is incorrect and the property you are trying to access in the view does not exist.
Please try out the following changes:
Products.php:
public function category()
{
return $this->belongsTo('App\Models\Category', 'catid', 'id');
}
view:
{{ $product->category->categoryname }}
One To Many (Inverse) / Belongs To
Simple follow Laravel conventions and you avoid to your problems in the future.
https://github.com/alexeymezenin/laravel-best-practices#follow-laravel-naming-conventions
Table structure:
categories
id - integer
name - string
products
id - integer
category_id - integer
name - string
Category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function products()
{
return $this->hasMany(Product::class);
}
}
Product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name'];
public function category()
{
return $this->belongsTo(Category::class);
}
}
Routes
Route::get('products', [ProductController::class, 'index']);
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::with('category')->get();
return view('product.index', compact('products'));
}
}
index.blade.php
<table>
<tbody>
#foreach ($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->category->name }}</td>
</tr>
#endforeach
</tbody>
</table>

Sync function in laravel not working as expected

I have an edit form which should update an activity with selected categories, but the sync function isn't working as expected.
It adds the selected checkboxes to the database but doesn't delete the old values. Resulting in mutliple of the same values in the pivot table.
form code:
<p class="activiteit-categorie">
<label>categorie</label>
#foreach ($categories as $categorie)
<div class="categorie-input">
<input type="checkbox" name="categories[]" value="{{ $categorie->id }}"><label for="categorie">{{$categorie->name}}</label><br>
</div>
#endforeach
</p>
controller code:
if ($request->has('categories')) {
$activiteit->categorie()->sync($request->input('categories'));
} else {
$activiteit->categorie()->detach($request->input('categories'));
}
return redirect()->route('active-overview')->with('message', 'Activiteit is succesvol aangepast!');
models categorie:
namespace App;
use Illuminate\Database\Eloquent\Model;
class categorie extends Model
{
protected $fillable = [
'name'
];
public function activiteit() {
return $this->BelongsToMany('App\activiteit');
}
}
model activiteit:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class activiteit extends Model
{
protected $fillable = [
'name', 'image', 'intro', 'goal', 'traject', 'extra_info', 'duration', 'price'
];
public function categorie() {
return $this->belongsToMany('App\categorie');
}
}
You can try this
class categorie extends Model{
protected $fillable = [
'name'
];
public function activiteit() {
return $this->BelongsToMany('App\activiteit','pivot_table_name','categorie_id','activiteit_id');
}
}
Use like this another Model
if ($request->has('categories')) {
$activiteit->categorie()->sync($request->categories);
} else {
$activiteit->categorie()->detach($request->categories);
}
It works fine for me
So after trying some stuff out I came up with a simple solution to my problem.
I first detach all the categories from the selected activity and then add selected categories to the pivot table.
$activiteit->categorie()->detach();
if ($request->has('categories')) {
$activiteit->categorie()->sync($request->categories);
}

ErrorException (E_ERROR) Trying to get property 'title' of non-object - Laravel 5.7

I'm using laravel 5.7, there is a relation that each student belongs to one program and I'm trying to get the specific student program title using {{ $student->programs->title }}
But there is an error
ErrorException (E_ERROR)
Trying to get property 'title' of non-object (View:D:\Work\UnitOne\BackEnd\UniLara\resources\views\admin\students\index.blade.php)
This is my Student Model
<?php
class Student extends Model {
protected $fillable = [
'name', 'country', 'program_id', 'image'
];
public function programs() {
return $this->belongsTo(Program::class);
}
}
and this is my programs Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Program extends Model {
protected $fillable = [
'title', 'description', 'image'
];
public function students() {
return $this->hasMany(Student::class);
}
}
Here is my StudentsController
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Students\CreateStudentsRequest;
use App\Http\Requests\Students\UpdateStudentsRequest;
use App\Program;
use App\Student;
use Illuminate\Http\Request;
class StudentsController extends Controller {
public function index() {
return view('admin.students.index')->with('students', Student::paginate(5));
}
}
and this is the last thing is the blade, Here's where I got the problem when I call {{ $student->programs->title }}
#foreach($students as $student)
<tr>
<td><img src="{{ asset($student->image) }}" alt="{{ $student->image }}"></td>
<td>{{ $student->name }}</td>
<td>{{ $student->country }}</td>
<td>{{ student->programs->title }}</td>
</tr>
#endforeach
Change your relation name. Laravel looks for an column in the database like relation_primarykey if you don't specify a foreign key in the relationship definition. in your case your relation is programs but your database column is program_id. an extra s is causing the problem. So use either of the following.
public function program()
{
return $this->belongsTo(Program::class);
}
Or
public function programs()
{
return $this->belongsTo(Program::class, 'program_id');
}
Laravel Docs

Append new element to eloquent collection

I have two tables posts and photos. Each post has 5 photos. I want to list in view each post with one photo (profile pic), first picture.
$published_post = Post::where('created_by',auth()->user()->id)
->where('status','published')
->get();
$photo = Photo::where('post',$published_post->id)->get();
These two gives me two different collection. How can I add the first photo of a particular post to its array so in view I can display using a foreach loop.
This is how I want in view:
#foreach($published_post as $item)
{{ $item->title }}
{{ $item->profile_photo }}
#endforeach
I tried put and push, but doesn't seem to be working. Not sure how exactly does we append a new key value pair to an object.
My two models:
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->timestamps();
});
Schema::create('photos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image');
$table->integer('post');
$table->timestamps();
});
class Post extends Model
{
protected $table = 'posts';
}
class Photo extends Model
{
protected $table = 'photos';
protected $fillable = ['image', 'post'];
}
Post Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/*This is used to specify the table which this model is associated with*/
protected $table = 'posts';
protected $fillable = [
'title'
];
public $timestamps = true;
public function photos(){
return $this->hasMany(Photos::class,'post');
//post is the foreign key for posts table
}
}
Photo Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
/*This is used to specify the table which this model is associated with*/
protected $table = 'photos';
protected $fillable = [
'image', 'post'
];
public $timestamps = true;
}
View:
#foreach($published_post as $item)
{{ $item->title }}
{{ $item->photos->first()->image }} // photos relation is invoked and fetched first image
#endforeach
You need to create 2 Models, one for Posts and one for Photos.
php artisan make:model Post
php artisan make:model Photo
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
//
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
//
}
Then create a hasMany relationship on the Post model to link to the Photo model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Photo;
class Post extends Model
{
public function photos()
{
return $this->hasMany(Photo::class);
}
}
Then in your view you can lazy load the photos whenever you like
#foreach($posts as $post)
{{ $post->title }}
{{ $post->photo[0]->name}}
#endforeach
The syntax to go in your view will be slightly different, but this gives you a good idea on how the functionality should work.
Ok, first you should change your Post model like this:
class Post extends Model
{
protected $table = 'posts';
public function photos()
{
return $this->hasMany(Photo::class, 'post');
}
}
And then, add the following to your Photo model:
class Photo extends Model
{
protected $table = 'photos';
public function post()
{
return $this->belongsTo(Post::class, 'post');
}
}
With this, you've created the relation between your models, and now you can get your data this way:
$published_post = Post::where('created_by',auth()->user()->id)
->where('status','published')
->with('photos')
->get();
And in your view, you can get the first photo this way:
#foreach($published_post as $item)
{{ $item->title }}
{{ $item->photos()->first()->name }}
#endforeach
For more info on relations, you might want to read the docs.
I hope this helps!

Logical complex insert into 2 following tables - Laravel

I have a house management project and i am trying to execute a complex function that consists of:
Each time i insert a new Bill into the DB, another table will be filled creating a new row for each share of this bill according to the number of flatmates this house has. I managed to insert into the Bills table but the program returns me to the expected page but with no insert into the Shares table. Not sure if logically i'm doing alright. The code bellow is how i tried to retrieve information of the last insert into the Bills table, which should then have its objects properties used into the Shares table. Does someone have any clue on how i can i proceed?
This is my controller function:
public function store(Request $request){
$bill = Bill::create($request->all());
$users = User::where('house_id', Auth::user()->house->id);
$nflatmates = Auth::user()->house->nflatmates;
$shared_amount = $bill->bill_amount / $nflatmates;
foreach($users as $user){
$data = ['user_id'=>$user->id,
'bill_id'=>$bill->id,
'share_amount'=>$shared_amount];
Share::create($data);
}
return redirect('/admin/bills');
}
This is my form blade. I believe the problem doesnt come from here. Just in case.
{!! Form::open(['method'=>'post', 'action'=>'AdminBillsController#store']) !!}
<div class="form-group' has-error' : '' }}">
<div class="col-md-6">
{!! Form::text('description',null,['class'=>'form-control', 'placeholder'=>'Bill Description']) !!}
</div>
</div>
<div class="form-group' has-error' : '' }}">
<div class="col-md-6">
{!! Form::number('bill_amount',null,['class'=>'form-control', 'placeholder'=>'Amount', 'required|between:0,99.99']) !!}
</div>
</div>
<input type="hidden" name="house_id" value="{{Auth::user()->house->id}}">
<br>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
{!! Form::close() !!}
These are my relationships:
This is the Share Model
<?php
namespace App;
use App\User;
use App\Bill;
use Illuminate\Database\Eloquent\Model;
class Share extends Model{
protected $fillable = [
'id', 'user_id', 'bill_id', 'share_amount', 'share_status'
];
public function user(){
return $this->belongsTo('App\User');
}
public function bill(){
return $this->belongsTo('App\Bill');
}
}
And this is the Bill Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\House;
use App\User;
use App\Share;
class Bill extends Model{
protected $fillable = [
'id', 'description', 'bill_amount', 'house_id'
];
public function house(){
return $this->belongsTo('App\House');
}
public function share(){
return $this->hasMany('App\Share');
}
}
This is the User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\House;
use App\Role;
use App\Task;
use App\Share;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'id','name', 'email', 'is_active','house_id','role_id','password',
];
protected $hidden = [
'password', 'remember_token',
];
public function house(){
return $this->belongsTo('App\House');
}
public function role(){
return $this->belongsTo('App\Role');
}
public function task(){
return $this->hasMany('App\Task');
}
public function share(){
return $this->hasMany('App\Share');
}
}
And this is the house Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
use App\Bill;
class House extends Model {
protected $fillable = [
'id','house_address', 'house_admin', 'nflatmates'
];
public function user(){
return $this->hasMany('App\User');
}
public function bill(){
return $this->hasMany('App\Bill');
}
}
The thing is that you obviously have oneToMany relationship there, so what you want to do is something like this.
public function store(Request $request){
$bill = Bill::create($request->all());
$users = User::where('house_id', Auth::user()->house->id);
$nflatmates = Auth::user()->house->nflatmates;
$shared_amount = $bill->bill_amount / $nflatmates;
foreach($users as $user){
$data = [
'share_amount' => $shared_amount,
'share_status' => 'XXXXXX'
];
$share = new Share($data);
//Associating user with this share
$share->user()->associate($user);
//Associating bill with this share
$share->bill()->associate($bill);
//Saving share
$share->save();
}
return redirect('/admin/bills');
}
EDIT:
In order for the code above to work, you must have a valid relationships set across your models.
EDIT 2:
I thought that nflatmates was a oneToMany relationship, but it isn't so there is no need for attach function.
We are now creating a Share object and through it's relationships that are defined we are using associate function based on Belongs To Relationships which you can find on official docs, just scroll down a bit.

Categories