I try to print on my view all the atleti associated with a squadra x but the method $squadra->atleti() always returns me ant empty array.
Have you got some ideas to get this working?
Down below you can find my code and my db structure.
Squadra is team in english. One team can be associated to many atleti (it stands for players).
I think there is some problems with the foreign key.
Thank you for your help.
<?php
//Squadra Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Squadra extends Model
{
protected $connection = 'custom_mysql';
protected $table = 'squadra';
/**
* Get the Allenatore for the Squadra.
*/
public function allenatore()
{
return $this->belongsTo('App\Models\Allenatore');
}
/**
* Get the Atleta for the Squadra.
*/
public function atleti()
{
return $this->hasMany('App\Models\Atleta');
}
}
<?php
//Atleta Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Atleta extends Model
{
protected $table = 'atleta';
protected $connection = 'custom_mysql';
/**
* Get the Atleta for the Squadra.
*/
public function squadra() {
return $this->belongsTo( 'App\Models\Squadra' );
}
}
<?php
//Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class AtletaController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function getSquadra($id)
{
$squadra = Squadra::find($id);
return view('custom.squadra.dettaglio', compact('squadra'));
}
//View
#foreach( $squadra->atleti() as $atleta )
<tr class="success">
<td>{{ $atleta->id }}</td>
<td>{{ $atleta->nome}}</td>
<td>{{ $atleta->cognome}}</td>
</tr>
#endforeach
Here it is the output of dd($squadra)
Your are sending the atleti to the view, instead of the squadra. Try to change your controller function to this:
public function index()
{
$squadra = Squadra::firstOrFail(); // You need a paremeter in a route that defines which squadra to show. This will show the first one.
return view('custom.atleta.index', compact('squadra'));
}
Related
I am trying to create a filter in Laravel.
I want to filter on the database field transmission but it is not working.
Here is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Occasion extends Model
{
protected $table = 'hexon_occasions';
public $primaryKey = 'id';
public $timestamps = true;
}
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use EloquentBuilder;
use App\Occasion;
class OccasionController extends Controller
{
public function index(Request $request)
{
$occasions = EloquentBuilder::to(
Occasion::class,
$request->all()
);
return $occasions->get();
}
public function show($slug)
{
$occasions = Occasion::where('slug', $slug)->first();
return view('occasions.show')->with('occasions', $occasions);
}
}
The filter:
namespace App\EloquentFilters\Occasion;
use Fouladgar\EloquentBuilder\Support\Foundation\Contracts\Filter;
use Illuminate\Database\Eloquent\Builder;
class TransmissionFilter implements Filter
{
/**
* Apply the age condition to the query.
*
* #param Builder $builder
* #param mixed $value
*
* #return Builder
*/
public function apply(Builder $builder, $value): Builder
{
return $builder->where('transmission', $value);
}
}
And the URL i am using is: https://www.laravel.bvdodev.nl/occasions?filter[transmission]=H
But I am getting the error: Not found the filter: FilterFilter
Does someone know what I am doing wrong?
Thanks for your time!
I am trying to learn more about Laravel ORM and ORM in general,
but I have problems I can't solve by myself.
This is my users table:
And here is my Article table:
My User eloquent model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
public function article()
{
return $this->hasMany('\App\Models\Article', 'autor_id');
}
}
And my Article eloquent model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'clanky';
public function autor() {
return $this->belongsTo('\App\Models\User', 'id');
}
}
I am trying to access each article with its author data using this code:
$articles = Models\Article::all();
foreach($articles as $art)
{
echo $art->autor->name . "<br>";
}
The problem is the model is returning only userdata from first article, not the second and so on.
Any thoughts on what could cause this? Thanks in advance.
I think you need to update your code like.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'Article';
public function autor() {
return $this->belongsTo('\App\Models\User', 'autor_id', 'id');
}
}
$articles = Models\Article::with('autor')->get();
foreach($articles as $art)
{
echo $art->autor->name . "<br>";
}
I have two models as Project and Collaborator this is My tables
Project column
id
project_name
project_note
user_id
Collaborator Model
id
project_id
collaborator_id
I need join this models to get project_name instead project_id of Collaborator Model.
how can I do this. I read www.laravel.com documents but difficult to understand. help me in code...
project Model
<?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
/*
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['project_name', 'project_notes', 'project_status', 'due_date'];
public function scopePersonal($query)
{
return $query->where('user_id', Auth::user()->id);
}
//
}
collaborator Model
<?php
namespace App;
use Auth;
use Illuminate\Database\Eloquent\Model;
class Collaboration extends Model
{
protected $table = 'project_collaborator';
/*
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['project_id', 'collaborator_id'];
/*
* Get the user that is a collaborator on another project
* #return collection
*/
public function user()
{
return $this->belongsTo(User::class, 'collaborator_id');
}
/*
* Query scope to return information about the current project
* #param $query
* #param int $id
* #return query
*/
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function scopeColabo($query)
{
return $query->where('collaborator_id',Auth::user()->id);
}
}
Based on your comment, you need to add a relationship hasOne to your collaboration model:
class Collaboration extends Model
{
.....
public function project()
{
return $this->hasOne('App\Project');
}
.....
}
The method project() will define your relationship with your project model. And then you'll be able to get the collaboration project name like this:
$collaborations = Collaboration::with('project')->get();
foreach ( $collaborations as $collaboration ) {
echo $collaboration->project->project_name;
}
You can read more in the documentation.
In your Collaboration class add the followoing relation:
public function project()
{
return $this->belongsTo('App\Project');
}
And in your User class define a relation as:
public function collaborations()
{
return $this->hasMany('App\Collaboration', 'collaborator_id');
}
Then you can get all the collaborations of logged in user by:
$collaborations = auth()->user()->collaborations()->with('project')->get()
or
To get all collaborations you can so as:
$collaborations = Collaboration::with('project')->get();
In your view file:
#foreach ($collaborations as $collaboration)
{{ $collaboration->project->project_name }}
#endforeach
I'm new to Laravel 5 and I have some difficulties with pivot tables, controllers and repositories.
I have the tables 'users', 'sites', 'site_user', and here is what I have now :
App\Models\User
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
protected $table = 'users';
public function sites()
{
return $this->belongsToMany('App\Models\Site')
->withPivot('site_id', 'user_id', 'relation');
}
}
App\Models\Site
class Site extends Model {
protected $table = 'sites';
public function user()
{
return $this->belongsToMany('App\Models\User')
->withPivot('site_id', 'user_id', 'relation');
}
}
App\Repositories\SiteRepository
<?php namespace App\Repositories;
use App\Models\Site, App\Models\User;
class SiteRepository extends BaseRepository
{
/**
* The User instance.
*
* #var App\Models\User
*/
protected $user;
/**
* Create a new SiteRepository instance.
*
* #param App\Models\Site $site
* #return void
*/
public function __construct (Site $sites, User $user)
{
$this->model = $sites;
$this->user = $user;
}
/**
* Get sites collection paginate.
*
* #param int $n
* #return Illuminate\Support\Collection
*/
public function index($n)
{
return $this->model
->latest()
->paginate($n);
}
App\Http\Controllers\SiteController
<?php namespace App\Http\Controllers;
use App\Repositories\SiteRepository;
use App\Repositories\UserRepository;
use App\Http\Requests\SiteCreateRequest;
use App\Http\Requests\SiteUpdateRequest;
use App\Models\Site;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class SiteController extends Controller {
/**
* The SiteRepository instance.
*
* #var App\Repositories\SiteRepository
*/
protected $site_gestion;
/**
* The UserRepository instance.
*
* #var App\Repositories\UserRepository
*/
protected $user_gestion;
/**
* Create a new SiteController instance.
*
* #param App\Repositories\SiteRepository $site_gestion
* #param App\Repositories\UserRepository $user_gestion
* #return void
*/
public function __construct (SiteRepository $site_gestion, UserRepository $user_gestion)
{
$this->site_gestion = $site_gestion;
$this->user_gestion = $user_gestion;
$this->middleware('admin');
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(SiteRepository $site_gestion)
{
//$counts = $this->site_gestion->counts();
$sites = $site_gestion->index(25);
$links = $sites->render();
return view('back.sites.index', compact('sites'));
}
views\back\sites\table.blade.php
#foreach ($sites as $site)
[...some code...]
#endforeach
What I want to do is to get all the sites of the logged in user. I've tried many things, but none of them are working. And I'm still not sure where to put the code, repository or controller...
I've read tutorials about pivot in Laravel, and I've tried with some things like this in the repo, but it doesn't work...
$user = $this->user->find(auth()->user()->id); //This line is working
foreach ($user->sites as $site) {
return $site
->latest()
->paginate($n);
}
If you want all sites of a logged user simply do it like this:
$sites = Auth::user()->sites;
That's all you need to do to get to these sites. If you want to use query and pagination try like this:
$sites = Auth::user()->sites()->latest()->paginate($n);
So what you've done seems pretty close.
So you pretty much have it, when iterating over the sites they should be instances of the site model.
$user = auth()->user(); // This is a way of saying your first line without a db query for the user
foreach ($user->sites as $site) {
// each site in here is a site model
$site->pivot->relation;
}
The only other thing that looks slightly strange is how you've defined the pivots. Generally when calling withPivot you wouldn't define the joining ids, if you wish to vary from the defaults you can pass it as an argument to the belongsToMany like so.
return $this->belongsToMany('App\Models\User', 'site_user', 'user_id', 'site_id')
->withPivot('relation');
I'm trying to make a CRUD application in Laravel 5 to better understand how a php platform work ( first time using one ), but I keep getting the "Method [all] does not exist." error and I can't understand what i'm doing wrong. I have a table named 'products' in Mysql and what I'm trying to do, is to list all the entry's from within the table. I also have an index.blade.php that I will post if needed.
ProductsController.php
class ProductsController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$products = ProductsController::all();
return View::make('products.index')->with('products', $products);
}
Products.php
class Products extends Eloquent
{
}
routes.php
Route::resource('/', 'ProductsController#index');
Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a $table property on your model. [Ref]
So, you should rename your Products.php to Product.php (or define the $table property on your model).
Then you can retrieve all products:
$products = Product::all();
Product.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
//
}
ProductsController.php
<?php namespace App\Http\Controllers;
use App\Product;
class ProductsController extends Controller {
public function index()
{
$products = Product::all();
return View::make('products.index')->with('products', $products);
}
}
Why you write ProductsController to access all() function. To access all() function you must call Product model.
ProductsController::all();
Example
Product Model
class Product extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'products';
}
Product Controller
class ProductController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$products = Product::all();
return View::make('products.index')->with('products', $products);
}