I have this function in the Controller:
/**
*
* Edit Registration
*
*/
public function edit(Registration $id)
{
$logs = Log::where('registration_id', $id->id)->users()->get();
dd($logs);
return view('registrations_edit', ['registration' => $id, 'log' => $logs]);
}
The documentation says I can call
Log::where('registration_id', $id->id)->users()->get();
when I define users() in the Model.
public function users(){
return $this->belongsTo('App\User', 'id', 'user_id');
}
but when I call users() in the Controller i always get
Call to undefined method Illuminate\Database\Query\Builder::users()
What am I doing wrong?
Kind regards
I think you can try this :
public function edit(Registration $id)
{
$logs = Log::with('users')->where('registration_id', $id->id)->get();
dd($logs);
return view('registrations_edit', ['registration' => $id, 'log' => $logs]);
}
Hope this work for you
If your relations write in right way, try this:
$logs = Log::where('registration_id', $id->id)->users->get();
Related
I have a resource Controller with this index method like this:
public function index()
{
$args = [];
$args = array_merge($args, $this->data_creator(35, 12, 'book'));
$args = array_merge($args, $this->data_creator(37, 12, 'kit'));
$args = array_merge($args, $this->data_creator(38, 12, 'game'));
$args['menu_links'] = [
'books' => route('shopping-products.category', Category::find(25)->slug),
'videos' => route('shopping-products.category', Category::find(24)->slug),
'kits' => route('shopping-products.category', Category::find(23)->slug),
'games' => route('shopping-products.category', Category::find(22)->slug),
];
return view('frontend.shop.products.index', $args);
}
But it returns this error:
Trying to get property 'slug' of non-object
And when I dd(Category::find(25), Category::find(24), Category::find(23), Category::find(22)); I get NULL results.
Meaning that it can not find data with specified ids.
However there are 25 records stored at the categories table:
So what is going wrong here? How can I fix this issue?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
Here is Category.php Model:
class Category extends Model
{
use Sluggable, SoftDeletes;
protected $table = 'categories';
protected $primaryKey = 'cat_id';
protected $guarded = [];
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable()
{
return [
'slug' => [
'source' => 'cat_name'
]
];
}
public function path()
{
return "/products/categories/$this->slug";
}
public function children()
{
return $this->hasMany(Category::class, 'cat_parent_id', 'cat_id');
}
public function parents()
{
return $this->hasMany(Category::class, 'cat_id', 'cat_parent_id');
}
public function products()
{
return $this->belongsToMany(Product::class, 'category_products', 'ctp_cat_id', 'ctp_prd_id');
}
public function news()
{
return $this->belongsToMany(News::class, 'category_news', 'ctn_cat_id', 'ctn_nws_id');
}
public function galleries()
{
return $this->belongsToMany(Gallery::class, 'category_galleries', 'ctg_cat_id', 'ctg_gly_id');
}
public function uploaded()
{
return $this->hasMany(UploadedFile::class, 'upf_object_id', 'cat_id')->where('upf_object_type_id', '=', '107');
}
public function articles()
{
return $this->belongsToMany(Article::class, 'article_category', 'act_cat_id', 'act_art_id');
}
public function olympiadExam()
{
return $this->belongsToMany(OlympiadExam::class, 'olympiads_exams_categories', 'oec_ole_id', 'oec_cat_id');
}
public function olympiadExamQuestion()
{
return $this->belongsToMany(OlympiadExamQuestion::class, 'olympiads_exams_questions_categories', 'oes_cat_id', 'oes_oeq_id')->orderBy('oeq_number', 'asc');
}
public function attr_attributes()
{
return $this->hasMany(CategoryAttribute::class, 'category_id', 'cat_id');
} //
public function attr_product()
{
return $this->hasMany(Product::class, 'prd_cat_att_id', 'cat_id');
} //
public function couponRelation()
{
return $this->hasMany(couponRelation::class, 'object_id', 'cat_id')->where('object_type', 'product_category');
}
public function magazines()
{
return $this->belongsToMany(Magazine::class, 'category_magazine', 'category_id', 'magazine_id');
}
}
And when I do: dd(Category::where('cat_id', 25), Category::where('cat_id', 24), Category::where('cat_id', 23), Category::where('cat_id', 22)); I get this as result:
The problem is because you are using SoftDeletes so soft deleted models will automatically be excluded from query results. In your case, look like Category with id 22, 23, 24, 25 are soft deleted. To get it, you need to use withTrashed() as mentioned in the doc. For example:
Category::withTrashed()->find(22)->slug
per an answer above: if you are using soft deletes you need to add
Category::withTrashed()
However, you can wrap the command in an optional() helper function.
optional(Category::find(22))->slug
// if you are using soft delete
optional( Category::withTrashed()->find(22) )->slug
this will return null if 22 does not exist instead of throwing an exception error.
Recently I've started with Laravel 5.8 and I'm trying to make the edit button which will update the row from the database. and when the edit button click, Laravel raise an error like this
this is my Controller:
public function edit($id_book){
$book = Books::find($id_book);
return view('/books',['book'->$book]);
}
public function UploadEdit(Request $request){
DB::table('books')->where('id_book',$request->id_book)->update([
'judul' => $request->judul,
'gambar' => $request->gambar,
'kategori' => $request->kategori,
'deskripsi' => $request->deskripsi,
'ketersediaan' => $request->ketersediaan,
'lokasi' => $request->lokasi
]);
return redirect()->back();
}
this is my models:
class Books extends Model
{
protected $table = "books";
protected $primaryKey = "id_book";
protected $fillable = [
'judul',
'gambar',
'kategori',
'deskripsi',
'ketersediaan',
'lokasi'
];
}
I was trying to solve this problem with change edit function in the controller:
from this
public function edit($id_book){
$book = Books::find($id_book);
return view('/books',['book'->$book]);
}
to this
public function edit($id_book){
$book = Books::find($id_book);
return view('/books',compact('book'));
}
and this:
public function edit($id_book){
$book = Books::find($id_book);
return view('/books')->withBooks('$book');
}
but it doesn't work
I think error shows id_book is wrong.
You should use findOrFail() method.
public function edit($id_book){
$book = Books::findOrFail($id_book);
return view('/books',compact('book'));
}
Change your line 58 (edit() function's return statement) to:
return view('/books',compact('book'));
It seems you used -> instead => to assign value
Change
return view('/books',['book'->$book]);
to
return view('/books',['book' => $book]);
Try this
public function edit($id_book) {
$book = Book::find($id_book);
return view('books.edit', compact('book'));
}
Try this:
public function edit($id_book){
$book = Books::where('id_book', $id_book)->first();
return view('/books', compact('book'));
}
I'm trying to use Laravel's resources & Collection to build a small API.
I would like to recover all the posts of the categories
My relation on my model :
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function posts()
{
return $this->belongsToMany(Post::class, 'post_category');
}
Category controller :
public function index()
{
$categories = Category::all();
return (new CategoryCollection(CategoryResource::collection($categories)));
}
My categoryResource :
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'slug' => $this->slug
];
}
My CategoryCollection
public function toArray($request)
{
return [
'data' => $this->collection,
'posts' => PostResource::collection($this->whenLoaded('posts')),
];
}
I try to recover the posts of a category first. When I make the following command I get an error: Method ... relationLoaded does not exist
'posts' => PostResource::collection($this->whenLoaded('posts'))
What did I not understand?
I also created two PostCollection and PostResource files (basic, I did not modify them)
public function toArray($request)
{
return parent::toArray($request);
}
public function index()
{
$categories = Category::all();
return (CategoryResource::collection($categories));
}
this is might help , try this
and if you want to use posts resource
you need make posts resources
and inside the CategoryResource
'posts'=>PostResource::collection($this->posts)
cannot use Resource in Collection.
Use this
public function index()
{
$categories = Category::all();
return (new CategoryCollection($categories));
}
So the problem is that when I try to update my entity it finds it updates it but gets stuck in a loop probably and doesn't exit. When I check the database, even before the 60 seconds of execution time that I have expires, the values that I have changed are updated.
If i constantly refresh (and here is where it gets crazy) the updated at values for other lectures starts to change every second while it executes this loop.
When creating (not finding the id on the condition It creates it without a problem)
I have Lectures which looks like this:
class Lecture extends Model
{
use Searchable;
use SoftDeletes;
protected $primaryKey = 'id';
protected $touches = ['themes', 'educationTypes', 'subjects'];
protected $fillable= [
'name', 'description', 'user_id', 'field_id', 'approved'
];
public static function boot()
{
parent::boot();
static::saved(function ($model) {
$model->themes->filter(function ($item) {
return $item->shouldBeSearchable();
})->searchable();
});
}
public function user(){
return $this->belongsTo('App\User')->with('companies');
}
public function geographies(){
return $this->belongsToMany('App\Geography');
}
public function educationTypes(){
return $this->belongsToMany('App\EducationType', 'lecture_education_type')->withTimestamps();;
}
public function themes(){
return $this->belongsToMany('App\Theme','lecture_theme', 'lecture_id', 'theme_id')->withTimestamps();;
}
public function subjects(){
return $this->belongsToMany('App\Subject', 'lecture_subject')->withTimestamps();;
}
public function cases(){
return $this->belongsToMany(
'App\CompanyCase' ,
'case_company_lecture',
'lecture_id',
'case_id',
'id',
'id')->withTimestamps();
}
public function companies(){
return $this->belongsToMany(
'App\Company' ,
'case_company_lecture',
'lecture_id',
'company_id',
'id',
'id'
);
}
public function field(){
return $this->belongsTo('App\Field');
}
public function toSearchableArray()
{
$this->themes;
$this->user;
$this->educationTypes;
$this->subjects;
$this->geography;
return $this->toArray();
}
}
This is the controller:
public function storeLecture(Request $request) {
$lecture_id = $request->get('lecture_id');
// It gets stuck between the comments
$lecture = Lecture::updateOrCreate(['id' => $lecture_id],
[
'name'=> request('name'),
'description'=> request('description'),
'user_id'=> request('user_id')]
);
// and doesn't update the themes, edu types subjects and etc.
$company_id = $request->get('company_id');
$company = Company::find(request('company_id'));
$lecture->companies()->sync([$company->id]);
$eduTypes= $request->get('education_types');
$themes= $request->get('themes');
$subjects = $request->get('subjects');
$geographies = $request->get('geographies');
$lecture->themes()->sync($themes);
$lecture->educationTypes()->sync($eduTypes);
$lecture->subjects()->sync($subjects);
$lecture->geographies()->sync($geographies);
$n1 = new Notification();
$n1->send(request('user_id'), 1, 'new_lecture', $lecture->id);
$user = User::where('id', $request->id)->first();
$user_with_companies = $user->load('companies');
$slug = $user_with_companies->companies->first()->slug;
return response(['success' => true]);
}
This is the frontend method sending the request (in between I have a middleware checking if the user is admin (possible to create a lecture) based on the this.selectedExpert.id, which doesn't interfere).
createUpdateLecture() {
const url = `${window.location.origin}/lecture/create/${
this.selectedExpert.id
}`;
this.$http
.post(url, {
education_types: this.allEducationTypes
.filter(el => el.checked)
.map(a => a.id),
themes: this.allThemes.filter(el => el.checked).map(a => a.id),
geographies: this.allGeographies
.filter(el => el.checked)
.map(a => a.id),
subjects: this.allSubjects.filter(el => el.checked).map(a => a.id),
name: this.lecture.name,
description: this.lecture.description,
user_id: this.selectedExpert.id,
company_id: this.company.id,
lecture_id: this.lecture.id
})
.then(res => {
console.log(res);
this.$parent.showLectureCreateModal = false;
// window.location.reload();
});
}
As I can see what is happening I probably use the method really badly but I just want to understand it better for further usage.
After a few days of researching and testing it turns out that it is not the updateOrCreate method causing the problem because I tried with two different functions for creating and updating and the update function was still having the same problem.
The problem is created from Algolia which is used for searching based on different fields in the platform. Fx. in Themes
class Theme extends Model
{
use SoftDeletes;
use Searchable;
protected $touches = ['lectures'];
public function lectures(){
return $this->belongsToMany('App\Lecture');
}
public function toSearchableArray()
{
$this->lectures;
return $this->toArray();
}
}
Removing the searchable from the models did the trick!
I'm trying to do a double where on my table, but even if the arguments are correct I cannot view any result:
Here is my Review model:
class Reviews extends Model
{
protected $fillable=['id','product_id', 'user_id', 'rating', 'comment',
'approved', 'spam'];
public function user()
{
return $this->belongsTo(User::class);
}
public function product()
{
return $this->belongsTo(Product::class);
}
And this is my controller, where I pass the values and make the query;
a DD on the values shows them correctly:
public function storereview(Request $request){
$uid=Auth::user()->id;
$productID = $request->id;
$matchThese = ['product_id' => $productID, 'user_id' => $uid];
$result=Reviews::where($matchThese);
dd($result);
The DD of result shows this:
https://ibb.co/fSzRGH
I made a screenshot cause I can't indent this here.
What am I doing wrong? I don't understand! Thank you.
You need to use get() to actually execute the query:
$result = Reviews::where($matchThese)->get();
You need to use get() to get the result.
Reviews::where($matchThese)->get();