I've got two tables: a user table and a car table. When a user is logged in I want to show his cars, with lots of information. But how do I do this in the controller, including giving the right car information from that user? I have already set the relations but how do I receive the right information in the controller?
I was thinking about this:
$car = car()->user();
return view('cars.index',compact('usercar','car'));
Of course this is wrong, but what's the right way?
EDIT:
This is my controller and this is the index method:
use App\Car;
public function index()
{
$car = Auth::user()->Car;
return view('tickets.index',compact('usercar','car'));
}
This is my user model:
use App\Car;
public function car()
{
return $this->hasMany('App\Car');
}
This is my car model:
use App\User;
public function user()
{
return $this->belongsTo('App\User');
}
And this is my route:
Route::get('/tickets','TicketsController#index');
in Model.php line 893 at FatalErrorException->__construct() in
HandleExceptions.php line 133 at
HandleExceptions->fatalExceptionFromError() in HandleExceptions.php
line 118 at HandleExceptions->handleShutdown() in HandleExceptions.php
line 0 at Model->hasMany() in User.php line 39 at
User->rittenregistratie() in Model.php line 2658 at
Model->getRelationshipFromMethod() in Model.php line 2631 at
Model->getRelationValue() in Model.php line 2573 at
Model->getAttribute() in Model.php line 3291 at Model->__get() in
Controller.php line 30
EDIT:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Car extends Model
{
protected $table = 'Car';
protected $fillable = ['beginstand', 'eindstand', 'van','naar','bezoekadres','geredenroute','karakterrit','toelichting','kilomterszakelijk','kilomtersprive'];
public function User()
{
return $this->belongsTo('App\User');
}
}
Assuming your relations are correct you should be able to do this:
$cars = Auth::user()->cars; // cars being the name of the relation method
return view('cars.index', compact('cars'));
Since you said "show his cars" I'm guessing one user can have many cars, so expect $cars to be a collection and not a single model.
Related
I have 3 tables
User (id,name,mail,mobile)
Contest (id,contest_name,contest_description)
Contest_user (id,user_id,contest_id)
I want to write a has many contest user method in the contest model also I need the user details from the method.
Kindly tell me how can I get the desired result.
Model Screenshot
<?php
namespace App\Model\Contest;
use App\Model\Project\ContestUsers;
use Illuminate\Database\Eloquent\Model;
class Contest extends Model
{
protected $table = 'contest';
protected $fillable = ['name','description'];
public $dates = [
'created_at',
'updated_at',
'deleted_at',
];
//I want to get user details from this method
public function project_contest_users()
{
return $this->hasMany(ContestUsers::class, 'contest_id', 'id')->whereNull('deleted_at');
}
}
contest_user is a pivot table for users and contests and should not have a model class.
The nature of the relation between User and Contest is a many to many, so you need to use belongsToMany() relation in both sides
Contest.php
public function users()
{
return $this->belongsToMany(User::class);
}
User.php
public function contests()
{
return $this->belongsToMany(Contest::class);
}
From what you have done, based on my experience, it's already a good thing that you normalize the many to many relationship. But what N69S said is also correct, that pivot table should not have a Model class, so you need to make your own convention to not use the Model class to create/update/delete (read is fine by me) and if you still want to stick to this method, what you need to do now is just defining the relationships for each of the Models.
User.php:
public function contest_user()
{
return $this->hasMany(ContestUser::class);
}
ContestUser.php:
public function user()
{
return $this->belongsTo(User::class);
}
public function contest()
{
return $this->belongsTo(Contest::class);
}
Contest.php:
public function contest_user()
{
return $this->hasMany(ContestUser::class);
}
I want to create a relation between lising and attribute table in laravel for that i have used following code to establish relationship between them but the data in my view is not coming from both the tables. I'm getting following error:
Call to undefined relationship [adListAttributes] on model
[App\Models\AdListing].
Here listing can have as many attribute associated with and attributes
can be associated to many listings
ad_listings:
id
title
name
date
ad_list_attributes table :
id
listing_id
name
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListAttribute extends Model
{
protected $table = "ad_list_attributes";
public function Listings()
{
return $this->belongsToMany('AdListing', 'id', 'listing_id');
}
}
namespace App\Models;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
class AdListing extends Model
{
protected $table = "ad_listings";
public function Attributes()
{
return $this->belongsToMany('AdListAttribute', 'listing_id', 'id');
}
}
Problem is that you are using belongsToMany in both the models.This will cause a problem.
In AdListAttribute model,
public function listing_information()
{
return $this->belongsTo('App\AdListing', 'id', 'listing_id');
}
In AdListing model,
public function adlisting_attributes()
{
return $this->hasMany('App\AdListAttribute', 'listing_id', 'id');
}
You can get the results using,
$response = AdListing::get();
if($response->adlisting_attributes)
{
foreach($response->adlisting_attributes as $attribute)
{
echo $attribute->name;
}
}
Problem is that ur not calling the relationship with the right name i assume
$listings = AdListing::with('Attributes')->get();
Update :
Try this :
use App\Models\AdListAttribute;
//
return $this->belongsToMany(AdListAttribute::class, 'listing_id', 'id');
Same for other model, then try
today i'm trying to get modulus operator in where laravel clause but i can't get it work and after make some google researches and read the documentation i post this may be some one can help me to get a solution
Produit::has('caracteristique.image', '=', 2)
//->where('(caracteristique.image.caracteristique_id)', '=', 2)
->has('caracteristique.stock')
->where('market_id', Auth()->user()->market->id)
->where(DB::raw('count(`produits`.`caracteristiques`.`images`.`caracteristique_id`)'), '%2', [2])
->get();
i hope to select all products that have a relation with caracteristique table and for each caracteristique i have to find 2 iamge that come from the images table
i make this also
->has('caracteristique.image', '=', 2)
but the problem is this code is not ensure for each caracteristique like i can get 1 product with 2 caracteristique and 3 image but i suppose to have 4 image hope you understand my problem and hope you will help me to find a solution. thank you
here we have the models
produit
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\{
Market,
Caracteristique,
};
class Produit extends Model
{
protected $fillable = ['nom', 'detail', 'rabais', 'statut','demande', 'market_id'];
public function caracteristique()
{
return $this->hasMany(Caracteristique::class);
}
public function market()
{
return $this->belongsTo(Market::class);
}
}
caracteristique
namespace App\Models;
use App\Models\{
Produit,
Stock,
Image,
};
use Illuminate\Database\Eloquent\Model;
class Caracteristique extends Model
{
protected $fillable = [
'produit_id', 'couleur', 'prix', 'quantite', 'size', 'disponible',
];
public function produit()
{
return $this->belongsTo(Produit::class);
}
public function stock()
{
return $this->hasOne(Stock::class);
}
public function image()
{
return $this->hasMany(Image::class);
}
}
image
namespace App\Models;
use App\Models\{
User,
Caracteristique,
};
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $fillable = [
'caracteristique_id', 'user_id', 'nom'
];
public function caracteristique()
{
return $this->belongsTo(Caracteristique::class);
}
public function user(){
return $this->belongsTo(User::class);
}
}
produit can have multiple caracterisque but for each caracteristique it must have 2 images how i can i write this query to avoid query caractristique with one or doesn't have any image please?
and it just say error sql at line one after the %2 condition.
I get the following error when checking subscription status with:
$user = User::where('id', '=', \Auth::user()->id)->first();
if ($user->subscribed('main')) <-- error
Error:
ErrorException in Builder.php line 2405: Call to undefined method
Illuminate\Database\Query\Builder::valid() (View: /var/www/html...
in Builder.php line 2405
at Builder->__call('valid', array())
at Builder->valid()
at call_user_func_array(array(object(Builder), 'valid'), array()) in Builder.php line 1426
at Builder->__call('valid', array())
at Builder->valid()
at call_user_func_array(array(object(Builder), 'valid'), array()) in Relation.php line 343
at Relation->__call('valid', array()) in Billable.php line 172
at HasMany->valid() in Billable.php line 172
at User->subscribed('main') in BillingsController.php line 58
at BillingsController->index()
I don't get any problems using the $user->onGenericTrial() and $user->onTrial() methods in the same view.
I've created a new subscription using:
$user = User::find(1);
$user->newSubscription('main', 'monthly')->create($creditCardToken);
I'm using Laravel 5.2 and Cashier 6.0 . I followed docs here https://laravel.com/docs/5.2/billing#checking-subscription-status .
In my user model, I use Laravel\Cashier\Billable; and use Billable; and hasMany on my Subscription model. My Subscription model has the belongsTo User relation
User model
<?php namespace App;
use Laravel\Cashier\Billable;
use Carbon\Carbon;
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract {
use Authenticatable, Authorizable, CanResetPassword;
public $incrementing = true;
use SoftDeletes;
use Billable;
protected $dates = ['deleted_at'];
protected $table = 'users';
protected $fillable = [ ... 'stripe_id', 'card_brand', 'card_last_four', 'trial_ends_at'];
public function subscription()
{
return $this->hasMany('App\Subscription');
}
public function getTrialEndsAtAttribute($value)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value, 'UTC')->setTimezone(\Helper::getTimezone());
}
This is where the error occurs:
https://github.com/laravel/cashier/blob/6.0/src/Billable.php
public function subscribed($subscription = 'default', $plan = null)
{
$subscription = $this->subscription($subscription);
if (is_null($subscription)) {
return false;
}
if (is_null($plan)) {
return $subscription->valid();
}
return $subscription->valid() &&
$subscription->stripe_plan === $plan;
}
Solution:
Finally found the problem! One must NOT create relationships between User and Subscription models. I had the hasMany relationship on my User model and the belongsTo relationship on the Subscription model. That was the problem.
Can you try and run:
$user->first()->subscribed('main');
See if this throws the same error, The reason im asking this is because the Illuminate query builder can throw undefined method if the full object is not instantiated.
Im not a laravel pro however i have faced this issue myself on several occasions, Let me give you an example of how i overcome a similar issue today.
return $user->payments()->first()->fetchMostRecent($customArrayValues)->first();
Also what does your $user->subscription(); or $user->subscription()->first(); return, does this function return what is expected?
As i said im by no means a pro with laravel however i will try and help out the best i can, I am sure more advanced people on here will also provide a helping hand as the query builder error exceptions can be a pain in the back side!
I have two tables named products_description with primary key products_id and second table orders_products with foreign key products_id that link these two tables. We can say that a product can be in many orders.
I have created the following models for both tables.
namespace App;
use Illuminate\Database\Eloquent\Model;
class products_description extends Model
{
protected $table = "products_description";
protected $primaryKey = "products_id";
public function orders_products()
{
return $this->belongsTo('App\Orders_product','products_id','products_id');
return $this->hasMany(Orders_product::class);
}
}
and
namespace App;
use Illuminate\Database\Eloquent\Model;
class Orders_product extends Model
{
protected $primaryKey = "orders_products_id";
}
The following code in my controller class
class products_controller extends Controller
{
public function show1(Products_description $Products_description)
{
return view('products.show',compact('Products_description'));
}
}
The following code in my show.blade.php file
#extends('layout')
#section('content')
{{ $Products_description->products_name }}
#foreach($Products_description->orders_products as $Orders_product)
{{ $Orders_product->orders_id }}
#endforeach
#stop
Where I want to display the product name first and then the order ids in which this products exists. But I am getting the following error. Without foreach loop, the product name is displaying fine.
Trying to get property of non-object (View: C:\wamp\www\laravel1\resources\views\products\show.blade.php)
in 0bb3f93ed324818ac22ad70d47add00a1c4f8a7c.php line 11
at CompilerEngine->handleViewException(object(ErrorException), '1') in PhpEngine.php line 44
at PhpEngine->evaluatePath('C:\wamp\www\laravel1\storage\framework\views/0bb3f93ed324818ac22ad70d47add00a1c4f8a7c.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'Products_description' => object(products_description))) in CompilerEngine.php line 59
at CompilerEngine->get('C:\wamp\www\laravel1\resources\views/products/show.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'Products_description' => object(products_description))) in View.php line 149
first this function have two returns, should remove first one:
public function orders_products()
{
return $this->belongsTo('App\Orders_product','products_id','products_id');
return $this->hasMany(Orders_product::class);
}
then in you controller function :
public function show1(Products_description $Products_description)
{
return view('products.show',compact('Products_description'));
}
you can't just compact('Products_description'), because it's an instance.
public function show1(Products_description $Products_description)
{
$products = $Products_description->all();
return view('products.show',compact('products'));
}
above is what you need , or just $products = $Products_description->find($productID);
I figured it out that I was using two relationships belongsTo and hasMany in my products_description model and was not using foreign_key and local_key in my hasMany relationship. Which was actually the problem. I removed the belongsTo relation and added the foreign_key and local_key to hasMany relation and it worked like a charm.