Model ListDeals
class ListsDeals extends Model
{
protected $table = "deals";
protected $fillable = ['title', 'slug', 'description', 'price', 'has_discount', 'price_to_discount', 'price_reduced', 'status', 'approved', 'suspended', 'start_date', 'end_date'];
public function lists()
{
return $this->belongsToMany('App\Models\Lists', 'list_has_deals' , 'deal_id', 'list_id')->withPivot('list_id');
}
public function user(){
return $this->belongsTo('App\Models\User');
}
Model Lists
class Lists extends Model
{
protected $table = "lists";
protected $fillable = ['title', 'slug', 'short_description', 'description', 'website', 'email', 'phone', 'lat_map', 'lng_map', 'address_reference', 'video', 'renewal_date', 'status', 'approved', 'suspended'];
public function categories()
{
return $this->belongsToMany('App\Models\ListsCategories', 'list_has_categories' , 'list_id', 'category_id');
}
public function deals()
{
return $this->belongsToMany('App\Models\ListsDeals', 'list_has_deals' , 'list_id', 'deal_id');
}
public function user(){
return $this->belongsTo('App\Models\User');
}
Pivot Table list_has_deals
id
list_id
deal_id
Controller HomePageController
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Models\User;
use App\Models\Lists;
use App\Models\ListsCategories;
use App\Models\ListsDeals;
use DB;
class HomePageController extends Controller
{
public function homepage(){
$matchThese = [ 'suspended' => 0, 'status' => 1, 'approved' => 1 ];
$deals = ListsDeals::where( $matchThese )->limit( 3 )->offset( 0 )->orderBy( 'start_date' )->get();
return view( "homepage" )
->with( "deals", $deals );
}
}
I want get in the view the same categories of the list for the deal in the HomePageController, but i dont kwno thw way, i try with withPivot('list_id') but i dont get the id of the list, thank for the help.
Check out the section Retrieving Intermediate Table Columns
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
Related
I'm getting an error when rendering a model Blogs
My errors:
Call to undefined method App\Models\Blog::getContent()
Can you suggest what is the cause of the error.
Model code given below
namespace App\Models;
use App\Models\Categories;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
public $table = "blogs";
protected $fillable = [
'id',
'category_id',
'title_ru',
'title_ua',
'slug',
'img',
'img_min',
'url',
'duration',
'annotation_ru',
'annotation_ua',
'description_ru',
'description_ua',
'meta_ru',
'meta_ua',
'keywords_ru',
'keywords_ua',
'views',
'type_record',
'schedule',
'published',
'created_at',
'updated_at'
];
public function category()
{
return $this->belongsTo(Categories::class);
}
public function scopePublished($query)
{
return $query->where('published', true);
}
}
This code helps to call the model Blog.
Hey there stackoverflow
I am currently building a course application as part of my laravel project.
My problem lies in how the eloquent handle model relations, i'm still kinda new to eloquent, so hopefully you can answer my question.
The structure
The Course has many episodes and each episode has many sections.
Which means I have 3 tables in the DB. Courses -> course_episodes -> course_episode_sections
ID table is where i connect courses with users - course_users.
Right now i can create courses and and put in all the data correctly.
The Problem
I need to retrieve all the courses and its nested children that the user has bought, which is connected in the course_users table with columns course_id and user_id
Course structure
Same stucture in DB
course: {
name: null,
sub_title: null,
estimate: null,
trailer: null,
type: null,
text: null,
course_episodes: [
{
name: null,
section: [
{
order: null,
type: null,
content: null,
},
]
},
]
}
Model Pictures
My models as of right now.
class CourseUsers extends Model {
protected $fillable = [
'id',
'course_id',
'user_id',
'active',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courses()
{
return $this->belongsToMany(Course::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function scopeFindForUserId($query, $userId)
{
return $query->where(function ($q) use ($userId) {
$q->where(function ($q) use ($userId) {
$q->where('user_id', $userId);
});
});
}
Course model
class Course extends Model{
protected $fillable = [
'id',
'name',
'sub_title',
'type',
'estimate',
'trailer',
'gateway_id',
'text',
'active',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courseEpisode()
{
return $this->hasMany(CourseEpisode::class);
}
public function courseUsers() {
return $this->hasMany(CourseUsers::class);
}
public function scopeActive(Builder $builder)
{
return $builder->where('active', true);
}
Course episode Model
class CourseEpisode extends Model implements HasMedia {
use HasMediaTrait;
protected $fillable = [
'id',
'course_id',
'order',
'name',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function course()
{
return $this->belongsTo(Course::class);
}
public function courseSection()
{
return $this->hasMany(CourseEpisodeSection::class);
}
Course episode sections
class CourseEpisodeSection extends Model {
protected $fillable = [
'id',
'course_episode_id',
'order',
'type',
'content'
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courseEpisode()
{
return $this->belongsTo(CourseEpisode::class);
}
According to your explanation, course_users table holds many-to-many relationship between Course and User model. In case of a many-to-many relationship, you actually don't need a CourseUser model. This kind of table which holds many-to-many relationship is called pivot table. Read more from the Official Documentation
I am defining only the relationships with your Course, User, CourseEpisode, CourseEpisodeSection models.
Course.php
class Course extends Model
{
public function courseEpisodes()
{
return $this->hasMany(CourseEpisode::class);
}
public function users()
{
return $this->belongsToMany(User::class,'course_users')->withPivot('active');
}
}
CourseEpisode.php
class CourseEpisode extends Model
{
public function courseSections()
{
return $this->hasMany(CourseSection::class);
}
}
User.php
class User
{
public function courses()
{
return $this->belongsToMany(Course::class,'course_users')->withPivot('active');
}
}
If you want to get all the children relationships from a user, use nested eager loading :
$user_with_nested_course_data = User::with('courses.courseEpisodes.courseSections')->find($id);
im new to Laravel and have a relationship question.
The goal is to get all News where news.page_id = page.id AND page.pagetype_id = pagetype.id WHERE pagetype.component = news AND page.app_id = 1
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
}
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType', 'pagetype_id');
}
}
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsToMany('App\Models\Page', 'pagetypes', 'id', 'id');
}
}
// now i need All News Items where page.pagetype_id = pagetypes.id and patchtypes.component = news
// First Attempts are
Page::whereHas('pagetype', function ($q) {
$q->where('component', 'news');
})->where(['app_id' => 1])->get();
// result is all Pages which has the proper component news.
This is what i have tried yet, but in my attempt i'll only receive the proper pages but of course not the news.
My "current" solution is to get all the pages and then loop through News::where('page_id', $myPageId). But im pretty sure its possible to get a proper relationship to get also news.
I cant do any other model since there are many different pagetypes and components aswell.
Thanks so far.
You need to add relationship function to news model.
public function pages() {
return $this->belongsTo('App\Models\Page');
}
And call it through News model.
News::with('pages')->where('app_id',1);
First off all I think that you are wrong with you PageType relation
class PageType extends Model
{
protected $table = 'pagetypes';
protected $fillable = ['pagetype', 'component', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->hasMany('App\Models\Page');
// if i understood you correctly you haven't got any pivot table
}
}
Then you should link your News and Page like so
News.php
class News extends Model
{
protected $table = 'news';
protected $fillable = ['page_id', 'title', 'description', 'active', 'created_at', 'updated_at'];
public function page() {
return $this->belongsTo('App\Models\Page');
}
}
Page.php
class Page extends Model
{
protected $table = 'pages';
protected $fillable = ['app_id', 'unique_id', 'pagetype_id', 'title', 'picture_url', 'short_description', 'description', 'valid_since', 'valid_until', 'extras', 'active', 'created_at', 'updated_at'];
public function pagetype() {
return $this->belongsTo('App\Models\PageType');
}
public function news() {
return $this->hasMany('App\Models\News');
}
}
Then you can achieve your goal
News::whereHas('page', function($q) use($appId) {
$q->where('app_id',$appId);
})->whereHas('page.pagetype', function($q) {
$q->where('component', 'news');
})->get();
I have two tables:
1. User.
2. Post.
In post table i have saved the user information. So when I click on update, it should load the particular user data. It's get loaded but when i click on the save button to update save.It's showing the following Error.
FatalErrorException in PostController.php line 78: Call to undefined
function App\Http\Controllers\fill()
I think i have problem with my postUpdate controller. But I couldn't find the problem.
Here is my User model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function post()
{
return $this->hasOne('App\Post'); //Profile is your profile model
}
}
Here is my Post Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'first_name', 'middle_name', 'last_name','gender', 'dob','nationality','nid','email','phone_no','about_me'
];
public function user()
{
return $this->belongsTo('App\User'); //Profile is your profile model
}
}
And here is my post Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
class PostController extends Controller
{
public function getDashboard()
{
$posts = Post::all();
return view('dashboard',['posts'=>$posts]);
}
public function postCreate(Request $request){
$this->validate($request,[
'first_name'=> 'required|max:120',
'middle_name'=> 'required|max:120',
'last_name' => 'required|max:120',
'gender'=> 'required',
'dob'=>'required',
'nationality'=>'required',
'nid'=>'required',
'email' => 'required|email|unique:users',
'phone_no'=>'required',
'about_me'=>'required',
]);
$post = new Post();
$post->first_name = $request['first_name'];
$post->middle_name = $request['middle_name'];
$post->last_name = $request['last_name'];
$post->gender = $request['gender'];
$post->dob = $request['dob'];
$post->nationality = $request['nationality'];
$post->nid = $request['nid'];
$post->email = $request['email'];
$post->phone_no = $request['phone_no'];
$post->about_me = $request['about_me'];
$message='There was an Error';
if( $request->user()->post()->save($post)){
$message = "Profile Created successfully";
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
public function postUpdate(Request $request)
{
$this->validate($request,[
'first_name'=> 'required|max:120',
'middle_name'=> 'required|max:120',
'last_name' => 'required|max:120',
'gender'=> 'required',
'dob'=>'required',
'nationality'=>'required',
'nid'=>'required',
'email' => 'required|email|unique:users',
'phone_no'=>'required',
'about_me'=>'required',
]);
$request->user()->post()->update(fill($request->all())) ;
return redirect()->route('dashboard');
}
}
Here, you're getting a collection of posts:
$data=Post::all();
But you need to pass an array. Try to replace it with:
$data = $request->only('first_name', 'middle_name', 'last_name', 'gender', 'dob', 'nationality', 'nid', 'email', 'phone_no', 'about_me');
i'm developing an API but when I create the relations (Many to Many) and want to show in the index function I'm getting an error QueryException in Connection.php line 669 The error says:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'CTL_Tags.id' in 'on clause' (SQL: select `CTL_Tags`.*, `CTL_Resource_has_Tags`.`idResource` as `pivot_idResource`, `CTL_Resource_has_Tags`.`idTag` as `pivot_idTag` from `CTL_Tags` inner join `CTL_Resource_has_Tags` on `CTL_Tags`.`id` = `CTL_Resource_has_Tags`.`idTag` where `CTL_Resource_has_Tags`.`idResource` is null)
I believe my error is in my model because it's looking for id in CTL_Tags table when my id name in that table is idTag.
This is my CTL_Resource model
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class CTL_Resource extends Model {
public $timestamps = false;
protected $table = "CTL_Resource";
protected $hidden = [
'coachVisibility', 'thumbnail', 'tags', 'relatedTo',
'studentVisibility', 'isHTML','studentIndex', 'coachIndex',
'isURL', 'source', 'path', 'status', 'updateTime', 'isfolder',
'parentResource', 'idModifierUser'
];
protected $fillable = ['idResourceType','productionKey', 'tags', 'idCreatorUser', 'idModifierUser', 'idCreationCountry', 'title', 'description', 'URL', 'fileName', 'extension', 'quicktag', 'minimumAge', 'maximumAge', 'productionKey'];
public function creatorUser() {
return $this->belongsTo('Knotion\OPR_User', 'idCreatorUser');
}
public function creationCountry() {
return $this->belongsTo('Knotion\CTL_Country', 'idCreationCountry');
}
public function resourceType() {
return $this->belongsTo('Knotion\CTL_ResourceType', 'idResourceType');
}
public function quickTags() {
return $this->belongsToMany('Knotion\CTL_QuickTag', 'CTL_Resource_has_QuickTags', 'idResource', 'idQuickTag');
}
public function tags() {
return $this->belongsToMany('Knotion\CTL_Tag','CTL_Resource_has_Tags', 'idResource', 'idTag');
}
public function relatedTo() {
return $this->belongsToMany('Knotion\CTL_RelatedTo', 'CTL_Resource_has_RelatedTo', 'idResource', 'idRelatedTo');
}
}
and I just will show you the code of one of the relations
<?php
namespace Knotion;
use Illuminate\Database\Eloquent\Model;
class CTL_QuickTag extends Model {
protected $table = "CTL_QuickTags";
protected $fillable = ['name'];
protected $hidden = ['status', 'createTime', 'updateTime'];
public function resources() {
return $this->belongsToMany('Knotion\CTL_Resource', 'CTL_Resource_has_QuickTags', 'idResource', 'idQuickTag');
}
}
and this is my Controller
<?php
namespace Knotion\Http\Controllers;
use Illuminate\Http\Request;
use Knotion\Http\Requests;
use Knotion\Http\Requests\ResourcesRequest;
use Knotion\CTL_Resource;
use Knotion\CTL_Tag;
use Knotion\CTL_QuickTag;
use Knotion\CTL_RelatedTo;
use Knotion\CTL_ResourceType;
class ResourcesController extends Controller {
public function index(Request $request) {
$resources = CTL_Resource::paginate(10);
$resources->each(function($resources) {
$resources->tags;
$resources->quickTags;
$resources->relatedTo;
});
return response()->json(
$resources
);
I'll be so grateful who anyone can help me. Thank you so much.
Try to define
$primaryKey
in your model , with the correct column name
https://laravel.com/docs/5.2/eloquent#defining-models