I am trying to extend an app called eBot, which was originally made with Symfony 1.4. I am using Laravel 5.1.
What I am trying to do is return an array of "Teams" along with their season in the following format:
{TeamName}<small>{SeasonName}</small>
Here is my current code:
$teams = [];
foreach(eBotTeam::all() as $team)
{
$teamSeasonPivot = eBotTeamSeasonPivot::where('team_id', '=', $team->id)->get()->first();
$season = $teamSeasonPivot->season;
$teams[$team->id] = $team->name . '<small>' . $season->name . '</small>';
}
My models look like the following:
class eBotSeason extends Model
{
protected $table = 'seasons';
protected $connection = 'ebot';
protected $fillable = ['name', 'event', 'start', 'end', 'link', 'logo', 'active'];
public function matches()
{
return $this->hasMany('\Doesplay\Models\eBotMatch', 'season_id');
}
}
class eBotTeam extends Model
{
protected $table = 'teams';
protected $connection = 'ebot';
protected $fillable = ['name', 'shorthandle', 'flag', 'link', 'dp_team_id'];
}
class eBotTeamSeasonPivot extends Model
{
protected $table = 'teams_in_seasons';
protected $connection = 'ebot';
protected $fillable = ['season_id', 'team_id'];
public function team()
{
return $this->belongsTo('Doesplay\Models\eBotTeam');
}
public function season()
{
return $this->belongsTo('Doesplay\Models\eBotSeason');
}
}
When I die and dump $teamSeasonPivot or $season it works fine and displays a model as it should. However, if I try to put it into the array as shown above it returns a Trying to get property of non-object error on $season = $teamSeasonPivot->season;.
In the error dump it shows the array ($teams) as it should.
If anyone has any ideas why this happens please let me know.
Edit: Here is the actual error:
Line 20 is $season = $teamSeasonPivot->season;
Related
My model:
class Product extends Model
{
protected $table = 'Products';
protected $fillable = ['product_code', 'type', 'name', 'description', 'price', 'discount', 'image', 'image_alt'];
public function products()
{
return $this->hasMany('App\ProductSpecifics');
}
}
My controller code:
public function product($code)
{
$product = Product::where('product_code',$code)->get();
$productSpec = ProductSpecifics::where('product_code',$code)->get();
var_dump($product->name);
return view('pages.product', compact('product','productSpec'));
}
Error:
Property [name] does not exist on this collection instance
I tried using dd($product) and I noticed that there is a lot of information in there.
How do I extract only the attributes like name,type & etc ?
try this
dd($product->toArray());
model user
protected $table = "users";
protected $fillable = ['name', 'email', 'password' ];
protected $hidden = [
'password', 'remember_token',
];
public function solicitud(){
return $this->hasMany('App\solicitud');
}
Model tiposolicitud
protected $table = "tiposolicitud";
protected $fillable = ['nombre'];
public function solicitud(){
return $this->hasMany('App\solicitud');
}
Model solicitud ( principal )
protected $table = "solicitud";
protected $fillable = [..extract... 'tiposolicitud_id','users_id'....];
public function tiposolicitud(){
return $this->belongsTo('App\tiposolicitud');
}
public function User(){
return $this->belongsTo('App\User');
}
Controller ( extract)
use App\solicitud as VarModel;
use App\User;
use App\tiposolicitud ;
...
public function index()
{
$var1 = VarModel::all();
return view('private.solicitud.index',compact('var1'));
}
index.php
#foreach ($var1 as $var)
<tr>
<td>{{$var->id}}</td> // OK
<td>{{$var->user->name}}</td> //NOT OK
<td>{{$var->tiposolicitud}}</td> // OK
Trying to get property of non-object (View: C:\wamp64\www\issdgr\resources\views\private\solicitud\index.blade.php)
I have problem with app / user
I have persisted the id of the user but I can not find the name ..
HELP!!!!!
The error is on your blade view with the following statement:
$var->id
I think its a multi-dimension Std Class Object. So before iterating, put a print_r() to check the content of it.
And one more thing, laravel maintain cache of all views inside
your_project/storage/framework/views
with name like 2b026073a4c3afa6c3599efffe5361a356c89d88.php that's why it is showing error here.
I'm trying to build a query from a Repository in a Model with 2 where clauses.
This is the data I have in a MySql table:
id name environment_hash
1 online_debit abc
2 credit_cart abc
I want to query by name and environment_hash. To do this, I created the method findByHashAndMethod() (see below).
But when I use it in my controller, like this:
$online_debit = $this->ecommercePaymentMethodRepository->findByHashAndMethod($hash, 'online_debit')->first();
or this:
$credit_card = $this->ecommercePaymentMethodRepository->findByHashAndMethod($hash, 'credit_cart')->first();
I keep getting both rows and not only the ones filtered. What's wrong with the code?
This is my PaymentMethodRepository.php
class EcommercePaymentMethodRepository extends BaseRepository
{
public function findByHashAndMethod($hash = null, $payment_method)
{
$model = $this->model;
if($hash)
{
$filters = ['environment_hash' => $hash, 'name' => $payment_method];
$this->model->where($filters);
}
else
{
$this->model->where('environment_hash', Auth::user()->environment_hash)
->where('name', $payment_method);
}
return $model;
}
public function model()
{
return EcommercePaymentMethod::class;
}
}
And this is my model EcommercePaymentMethod.php
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class EcommercePaymentMethod extends Model
{
use SoftDeletes;
public $table = "ecommerce_payment_methods";
protected $dates = ['deleted_at'];
public $fillable = [
"name",
"payment_processor_id",
"active",
"environment_hash"
];
protected $casts = [
"name" => "string"
];
public function payment_processor()
{
return $this->hasOne('App\Models\EcommercePaymentProcessor');
}
}
While I am not entirely sure why ->first() would ever return more than one result, your Repository method had some few glaring issues that's prone to errors.
class EcommercePaymentMethodRepository extends BaseRepository
{
// 1. Do not put optional parameter BEFORE non-optional
public function findByHashAndMethod($payment_method, $hash = null)
{
// 2. Call ->model() method
$model = new $this->model();
// 3. Logic cleanup
if (is_null($hash)) {
$hash = Auth::user()->environment_hash;
}
return $model->where('environment_hash', $hash)
->where('name', $payment_method);
}
public function model()
{
return EcommercePaymentMethod::class;
}
}
MySQL tables:
posts
tags
post_tag (with columns post_id and tag_id)
// Post.php model
class Post extends Eloquent {
protected $table = 'posts';
public $timestamps = true;
protected $guarded = ['id'];
public function tags()
{
return $this->belongsToMany('Tag');
}
}
// Tag.php model
class Tag extends Eloquent {
protected $table = 'tags';
public $timestamps = false;
protected $guarded = ['id'];
public function posts()
{
return $this->belongsToMany('Post');
}
}
// on routes.php
Route::get('/', function()
{
$post = Post::find(44);
echo $post . '<br>';
$tag = Tag::find(28);
echo $tag;
return $post->tags;
});
when hitting / it prints post:44, it prints tag:28 and gives
ErrorException Cannot use a scalar value as an array
when accessing tags property that is on Post.php tags() function.
bare in mind that on post_tag's table there's an entry with post_id=44 and tag_id=28 but it could be empty.
Laravel/php gives me that error while trying to access the belongsToMany('Tag') method.
what am I doing wrong?
Should be fixed on February update: http://www.hhvm.com/blog/3287/hhvm-2-4-0
I believe you need to use eager loading:
$post = Post::with('tag')->find(28);
I don't have a laravel setup in front of me to test. So find might not be chainable, so you might need to do this:
$post = Post::with(array('tag' => function($query)
{
$query->where('id', '=', 44);
}))->get();
I'm having trouble figuring out how to access a nested relationship within Laravel. The specific example I have is a Movie that has many entires in my Cast table which has one entry in my People table. These are my models:
MOVIE
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
MOVIECAST
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public function person()
{
return $this->hasOne('Person', 'person_id');
}
public function netflix()
{
return $this->belongsTo('Movie', 'movie_id');
}
}
PERSON
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
In my controller I can access the cast (containing person_id and role_id) like so:
public function movie($id)
{
$movie = Movie::find($id);
$cast = $movie->cast();
return View::make('movie')->with(array(
'movie' => $movie,
'cast' => $cast
));
}
...but I don't know how to access the corresponding name field in my People table.
EDIT 1:
Using the classes exactly as defined below in #msturdy's answer, with the controller method above I try to render the person names like so inside my view:
#foreach($cast->person as $cast_member)
{{$cast_member->person->name}}
#endforeach
Doing this i get the error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$person
I don't know if it makes a difference or not but I have no id field on my People table. person_id is the primary key.
It should be simple, once you have accessed the cast...
Route::get('movies', function()
{
$movie = Movie::find(1);
$cast = $movie->cast;
return View::make('movies')->with(array(
'movie' => $movie,
'cast' => $cast));
});
Note: at this point, $cast is an instance of the Collection class, not a single object of the MovieCast class, as the
relationship is defined with hasMany()
you can iterate over it in the View (in my case /app/views/movies.blade.php
#foreach($cast as $cast_member)
<p>{{ $cast_member->person->name }}</p>
#endforeach
Class definitions used for testing:
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
public $timestamps = false;
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public $timestamps = false;
public function person()
{
return $this->hasOne('Person', 'person_id');
}
}
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public $timestamps = false;
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}