Display table data without user auth - php

I'm studying event message board. I can display table data by every Users own post. however I would like to display All post too. I wrote this as $tasksall but it didn't work. Could someone teach me what is wrong?
AController.php
public function index()
{
$tasks = Auth::user()
->tasks()
->orderBy('is_complete')
->orderByDesc('created_at')
->paginate(5);
$tasksall =
->tasks()
->orderBy('is_complete')
->orderByDesc('created_at')
->paginate(5);
return view('tasks', [
'tasks' => $tasks, 'tasksall' => $tasksall
]);
}
Task.php (model)
class Task extends Model
{
protected $casts = [
'is_complete' => 'boolean',
];
protected $fillable = [
'title',
'is_complete',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
AController.php I add this code
public function person()
{
return $this->belongsTo('App\Models\Task');
}
public function getData()
{
return $this->id . ':'/ $this->person->name.')';
}
index.blade.php I add this code
{{ $task2->getData() }}

You can just write a query to get all the task using eloquent to get all the tasks.
$tasksall = Task::all();
Have a look at this link.
Also for you case I think the problem is you are getting task from the User model so you $task will contain only task related to that particular user as you have a belongsTo relation of task with user.
For Your case to get name of User from task.
//Task model
class Task {
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
}
Then you can query like this in your controller.
$task = Task::find($id);
$name = $task->user->name;

Related

Laravel Eloquent persist 1:n

I want to create a laravel crud repository for a model. The model has 1 1:n and 1 n:n relationship.
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'description', 'merchantId', 'name', 'link', 'pictureUrl', 'ean', 'brand', 'aktPrice', 'affiliatePortal', 'programId'
];
public function prices() {
return $this->hasMany(Price::class);
}
public function categories() {
return $this->hasMany(Categorie::class);
}
}
Now I want to create a repository which has a save method and a controller for a restapi, which calls the save methode. My question is how should a save method looks that the entity is saved correctly and which mapping operations have to be done before that it works. I hope someone can help me and send me a save method, or a crud repository for my case and can help me to design the controller.
A Controller, with all the crud operations, look like this:
<?php
namespace App\Http\Controllers;
use App\Models\Room;
use Illuminate\Http\Request;
class RoomController extends Controller
{
public function index()
{
$rooms = Room::all()->toArray();
return $rooms;
}
public function add(Request $request)
{
$room = new Room;
$room->create($request->all());
return response()->json('The room successfully added');
}
public function getById($id)
{
$room = Room::find($id);
return response()->json($room);
}
public function update($id, Request $request)
{
$room = Room::find($id);
$room->update($request->all());
return response()->json('The room successfully updated');
}
public function delete($id)
{
$room = Room::find($id);
$room->delete();
return response()->json('The room successfully deleted');
}
}

Laravel Eloquent method updateOrCreate exceeds execution time when updating

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!

Laravel - Eloquent attach() not working for models

TL;DR
Trying to get three models to interact using eloquent for a rest api.
User - belongsToMany(pulls)
Pull - belongsToMany(user) && belongsToMany(boxes)
Box - belongsToMany(pulls)
The pull_user table is working perfectly, I can just attach a user after I save a pull. Saving a box works fine but the attach doesn't work/enter anything into the pivot table (I get no errors though).
The Problem
I can't get a pivot table that associates two of my models together to attach() after a save. I have the three models listed above, the pivot is working for pull_user but not for pull_box even though the save for box is working perfectly. I am able to save a box without an error but the association just never occurs (no error).
The Code
pull_box.php
class PullBox extends Migration
{
public function up()
{
Schema::create('pull_box', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('pull_id');
$table->integer('box_id');
});
}
public function down()
{
Schema::dropIfExists('pull_box');
}
}
Pull.php
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box');
}
}
Box.php
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull');
}
}
BoxController.php
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
...
]);
$user_id = $request->input('user_id');
...
$box = new Box([
'user_id' => $user_id,
...
]);
$pull = Pull::whereId($pull_id)->first();
if($box->save()){
$pull->boxes()->attach($box->id);
$box->view_box = [
'href' => 'api/v1/box/' . $box->id,
'method' => 'GET'
];
$message = [
'msg' => 'Box created',
'box' => $box,
'pull' => $pull_id
];
return response()->json($message, 201);
}
$response = [
'msg' => 'Box creation error, contact supervisor',
];
return response()->json($response, 404);
}
The Solution
I need to know how I can get this association working. I am going to need to add a new layer in under the pull for Item, but I don't want to move one before I solve this. I think that my problem has to stem from a syntactical/logical error on my part but I can't see it. There are a bunch of questions on SO that are very close to giving me a solution, but after reading them I wasn't able to solve my problem.
Any help is appreciated.
Try renaming your pull_box table to box_pull, pivot tables on laravel must be in alphabetical order. If you want to use custom name on pivot table you have to extends your pivot, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PullBox extends Pivot
{
protected $table = 'pull_box';
}
And your many to many relationships:
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box')->using('App\PullBox');
}
}
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull')->using('App\PullBox');
}
}

No query results for model ? But why?

like in the headline is written, I'm getting a :
No query results for model [App\Models\Thread\Comment].
Error message. I'm getting this error after I'm trying to delete a Thread. The funny thing is that this Error Message says "No results for the Comment Model. But I wan't to delete a thread, not a comment. It doesn't matter if the Thread have some comments or not, I'm getting this error message every time I try it. I can't really say why, cause I haven't changed the Comment Model. Can someone have a look over it?
My Comment model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public $table = 'comments';
public $fillable = [
'comment',
'thread_id',
'user_id',
];
public function commentuser()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
Thread Model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
public $table = 'thread';
public $fillable = [
'thread',
'content',
'user_id',
'themen_id',
];
public function userthread()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
public function threadthema()
{
return $this->belongsTo('App\Thread\Thema', 'thema_id', 'id');
}
}
The delete route:
Route::delete('/show/{id}', ['as' => 'destroycomment', 'uses' => 'Test\\TestController#destroycomment']);
The blade where the threads + the comments are:
http://pastebin.com/0NUPx18C
distroy method in controller:
public function destroy($id)
{
$thread = Thread::query()->findOrFail($id);
$thread->delete();
return redirect(action('Test\\TestController#startpage', [Auth::user()->id]));
}

Add values to pivot table laravel

When I want to save a reaction to a ticket I've three tables (in laravel):
-Tickets
-Reaction
-Reaction_Tickets (pivot table)
When I want to save a reaction I do it like this:
public function addReaction(Request $request, $slug)
{
$ticket = Ticket::whereSlug($slug)->firstOrFail();
$reaction = new reactions(array(
'user_id' => Auth::user()->id,
'content' => $request->get('content')
));
return redirect('/ticket/'.$slug)->with('Reactie is toegevoegd.');
}
But now of course it's not added to the pivot table. And I can't add it because I don't have a model of it. What's the right way of doing this?
EDIT:
-Tickets
public function reactions()
{
return $this->belongsToMany('App\reactions');
}
-Reactions
public function tickets()
{
return $this->hasOne('App\tickets');
}
From the Laravel documentation, you need to save and attach the Reaction to the Ticket:
$reaction = new reactions(array(
'user_id' => Auth::user()->id,
'content' => $request->get('content')
));
$reaction->save(); // Now has an ID
$tickets->reactions()->attach($reaction->id);
In your Ticket model, you need to have the relationship defined:
class Ticket extends Model {
protected $table = "tickets";
public function reactions(){
return $this->belongsToMany("App\Reaction");
}
}
And you should have the inverse defined on Reaction:
class Reaction extends Model {
protected $table = "reactions";
public function tickets(){
return $this->belongsToMany("App\Ticket");
}
}
If your models are set-up like so, you shouldn't have any issue attaching the new Reaction to your existing Ticket via your pivot table.

Categories