Laravel 5 - passing variable to relationship model - php

If I have below models:
class User extends Model{
protected $someDataFromExt = ['taskID0' => 'test', 'taskID1' => 'ting'];
public function tasks() { return $this->hasMany('Task'); }
}
class Task extends Model{
protected $appends = ['ext_data'];
public function user() { return $this->belongsTo('User'); }
public function getExtDataAttribute(){ return $this->external_data; }
}
I would like, when I do: $tasks = auth()->user()->tasks->all(); I want to pass $user->someDataFromExt (based on task ID) to task model, so I later in my $tasks variable I can access:
foreach($tasks as $task){
echo $task->ext_data;
}
Which will return data that was given from user model earlier?
Is this possible? how?

Not completely following why the task data is being stored on the user model, but I think what you’re asking can be achieved via your accessor method on your task model, providing you make the someDataFromExt public:
<?php
class Task extends Model {
public function getExtDataAttribute()
{
return $this->user->someDataFromExt['taskID' . $this->id];
}
}

Related

information about related models in Laravel

Hello I´m writing an API and I want to display more information about the related model.
Routes.php
Route::resource('makes', 'MakesController');
MakesController.php
class MakesController extends Controller
{
public function index()
{
$data = Make::all();
return response()->json($data);
}
}
This returns only information about the makes (id, name)
but how can I display also how many models has each make?
I have defined these two models
class Make extends Model
{
public function models()
{
return $this->hasMany('App\CarModel');
}
}
class CarModel extends Model
{
public function make()
{
return $this->belongsTo('App\Make');
}
}
You can define $visible field in the Make model's class like this:
protected $visible = ['models'];
This will automatically appends the related model's array to array/json.
You can also use an optional way with makeVisible method:
class MakesController extends Controller
{
public function index()
{
$data = Make::all();
return response()->makeVisible('models')->json($data);
}
}

Laravel5.2 with count

I have the following problem,
I have four models:
MainArea |Institute|institute_level|students with the following reations:
class MainArea extends Model
{
public function institute(){
return $this->belongsTo('\App\Institute');
}
public function places(){
return $this->hasMany('\App\Place');
}
}
class Institute extends Model
{
public function insLevel(){
return $this->hasMany('\App\InstituteLevel');
}
}
class InstituteLevel extends Model
{
public function students(){
return $this->hasMany('\App\Student','applying_level');
}
}
class Student extends Model
{
public function instituteLevel(){
return $this->belongsTo('\App\InstituteLevel','institute_level_id');
}
public function place(){
return $this->belongsTo('\App\Place');
}
}
Now, I want to get all areas with the count of students registered in it, in the same institute? it should be something like this.
$areas=\App\MainArea::withCount('institute.insLevel.students')->where('institute_id',$id)->get();
Any suggestions ?
Unfortunately, "withCount()" doesn't support nested relationships as of Laravel 5.2.
Here's the comment from the contributor in a Github Pull Request.

How to define the "follow" relationship in laravel 5.2

Recently I use Laravel to define the 'follow' relationship between users. Here are the models:
class User extends Model
{
public function follows()
{
return $this->morphMany('App\User', 'followable');
}
}
class Follow extends Model
{
public function followable()
{
return $this->morphTo();
}
}
and the database for Follow is like this:
follows:
- id:
- user_id:
- followable_id:
- followable_type:
all the above are defined according to the examples which Laravel documents provides.
And now I can retrieve the user model like this:
$follow = Follow:find(1);
$user = $follow->followable;
But when I write code like this:
$followers = $user->follows;
I get errors:
Relationship method must return an object of type
Illuminate\Database\Eloquent\Relations\Relation
here is my question:
Did I define the relationship of 'follow' right? and how can I fix the errors?
Thanks.
try this
class User extends Model
{
public function follows()
{
return $this->morphMany('App\User', 'followable');
}
}
change in to
class User extends Model
{
public function follows()
{
return $this->morphMany('App\Follow', 'followable');
}
}
because your have given model name is incorrect.

How can I organise classes in a Laravel 5 Project?

I am working on a Task Management App. In App there is a User Model and there is Project and Task models.
In order for user to add a Project and related Task, all I would do at Model Level is:
class Project extends Model
{
public function add($user_id,$task_details)
{
//Add Project Meta
$this->title = "Project Title";
$this->description "Desc"
$this->save()
for($t=0;$t<count($task_details);$t++) {
//Add Task Details
$task = new Task();
$task->title = $task_details["title"];
$task->description = $task_details["description"];
$task->save();
}
}
}
It looks clumsy to me. How can I improve this in Laravel 5? How can I make my modules more atomic?
Yeah it is clumsy. You should use Repository pattern so that there is no such type of multiple responsibilities.
And Eloquent already has a create method like findorCreate or just create method.
Here is simple example for UserRepository.
//UserRepository
<?php namespace App\Repository\User;
use App\User;
class UserRepository{
public $model;
public function __construct(User $userModel) // type hinting the User Model
{
$this->model=$userModel;
}
public function create($inputs)
{
return $this->model->create($inputs);
}
}
// UserController
<?php namespace App\Http\Controllers;
use \App\Repository\User\UserRepository;
class UserController extends Controller{
public $userRepo;
public function __construct(UserRepository $userRepository) //type hinting the userRepository Class
{
$this->userRepo=$userRepository;
}
public function getUser($id)
{
return $this->userRepo->model->findorfail($id);
}
public function getCreate()
{
if($this->userRepo->create(Input::all())
return view('success');
return Redirect->back()->withErrors();
}
}

Laravel Relationships Between Two Models

I am struggling with working with relationships right now and would like some help as for how to make this relationship work. I am using Laravel.
Lets say you have a staff model that looks like so:
Staff.php
class Staff extends \Eloquent {
protected $fillable = [];
public function status()
{
return $this->belongsTo('Staff_status');
}
}
The database table for the staff is as follows:
Table Name: staff
Fields: id, staffer_name, status_id
You also have a staff status model represented below:
Staff_statuses.php
class Staff_status extends Eloquent {
public function staff()
{
return $this->hasMany('Staff');
}
}
You also have a staff database table like so:
Table Name: staff_statuses
Fields: id, status_name
However when I try and load the staff controller index method it says class Staff_status is not found.
Any idea why?
You have used Staff_statuses.php as the name of your model but you are using Staff_status in the class name and thus you are calling it using Staff_status from your controller as well. This is the problem.
Change the file name to match the class name. For example, use something like this:
// StaffStatus.php
class StaffStatus extends Eloquent{
protected $table = 'staff_statuses';
public function staff()
{
return $this->hasMany('Staff');
}
}
// Staff.php
class Staff extends Eloquent {
protected $table = 'staff';
protected $fillable = [];
public function status()
{
return $this->belongsTo('StaffStatus');
}
}
In the controller you may use something like this:
$staffStatus = StaffStatus::all();
$staff = Staff::all();
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
class Staff extends Model
{
public function photos()
{
return $this->morphMany('App\Photo', 'imageable');
}
}
class Product extends Model
{
public function photos()
{
return $this->morphMany('App\Photo', 'imageable');
}
}

Categories