laravel 5.7 with() method - laravel

i'm trying to query two related model in the controller but the request failed.
here is my code:
$product = 'smartphone';
$prod = Produit::where('designation', $product)->with('tarifs')->get();
foreach($prod->tarifs as $tarif){
$tarif->prixAchat = $prix[$id];
$tarif->save();
}
this is the error message: Property [tarifs] does not exist on this collection instance.
i have this in the Produit model:
public function tarifs()
{
return $this->hasMany('App\Models\Tarif');
}
and the Tarif model:
public function produit()
{
return $this->belongsTo('App\Models\Produit');
}

you're getting a collection of products, and trying to get tarifs of it, thats why it throws the error, heres the solution
$product = 'smartphone';
$products = Produit::where('designation', $product)->get();
foreach($products as $prod){
foreach($prod->tarifs as $tarif){
$tarif->prixAchat = $prix[$id];
$tarif->save();
}
}

Related

why i can't call name from table food?

public function orderlist(Request $request){
$id = $request->id;
$data['order'] = Order::where('shop_id',$id)->orderBy('id')->get();
foreach($data['order'] as $orders){
$orders->shop = Shop::where('id',$orders->shop_id)->first();
$orders->food = Food::where('id',$orders->food_id)->get();
}
return $orders->food->name;
return view ('administrator.users.list_order.index',$data);
}
If you set up proper Eloquent relationships, this code could be rewritten like so:
public function orderlist(Request $request, Shop $shop){
$orders = $shop->orders()->with(['food'])->get();
return view ('administrator.users.list_order.index',compact('orders'));
}
Check out the docs here: https://laravel.com/docs/5.7/eloquent-relationships

Create Join Between Tables Laravel

I Have 2 tables : Posts - Comment
I Want to Make Relation Between These 2 Tables and Need to Update The Comment That Has "1" Post_ID :
Route:
Route::get('join', 'JoinController#Join');
Controller :
public function Join()
{
$Comment = Posts::find(1)->Comment;
$Comment->Title = "JOIN";
$Comment->save();
}
Posts Model :
public function Comment()
{
return $this->hasOne('App\Comment');
}
Comment Model :
public function Posts()
{
return $this->belongsTo('App\Posts');
}
but i recieve this error :
Trying to get property of non-object
Do this instead:
$comment = new Comment;
$comment->Title = 'JOIN';
#comment->post_id = 1;
$comment->save();
Or you can use create() method:
$Comment = Posts::find(1)->Comment()->create(['Title' => 'JOIN']);
If you'll use create() method, make sure Title is in the $fillable array.
$Comment = Posts::find(1)->Comment()->first();
$Comment->Title = "JOIN";
$Comment->save();

Laravel 4: Why can't I use aliases in my laravel code

Here's my code:
public function getReports()
{
$reports=DB::table('reports')
->select(array('*',DB::raw('reports.id','reports.departmentID','reports.officerID','reports.created_at','reports.report','reports.title','department.name','posts.name AS pname')))
->leftjoin('department','reports.departmentID','=','department.id')
->leftjoin('posts','reports.postID','=','posts.id')
->leftjoin('users','reports.officerID','=','users.id')
->leftjoin('events','events.id','=','reports.eventID')
->orderBy('reports.id','DESC')
->get();
$reportsArray=array();
foreach($reports as $row)
{
$reportsArray[]=array(
'id'=>$row->id,
'report'=>$row->report,
'title'=>$row->title,
'departmentName'=>$row->name,
'created_at'=>$row->created_at,
'post'=>$row->pname,
);
}
return View::make('reports.reports')
->with('reports',$reportsArray);
}
I'm getting the following error when I load the view: Undefined property: stdClass::$pname
This is basically a problem because i need to use aliases in many instances. And the error is basically the same when I try to use a column alias with any column. Can anyone see where the problem is with my code?
My Model:
class Report extends Eloquent
{
protected $table = 'reports';
protected $fillable= array(
'title','reportDate',,'departmentID','date','eventID','officerID','postID‌​',
);
}

Laravel ORM relationship returns error when value not present in DB

I have an issue with querying relationships.
I am querying relations between Projects, Companies and Products. However, whenever a Project ID is not present in the database an fatal exception is trown:
Call to a member function companies() on a non-object
public function index($i) {
return $this->returnTop($i, Array(
'projectid' => 5,
'products' => Array(1, 2, 3)
)
);
}
public function returnTop($count = 6, $args = Array()) {
$companies = Project::find($args['projectid'])->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
}
Now, I know that project id 5 is not present in the DB, and this is likely to be the cause of this error, but I want to return a message instead of the application throwing a fatal error....
Any ideas?
Just check if find() returns null. Something like this:
$project = Project::find($args['projectid']);
if(is_null($project)){
return Response::json(['message' => 'Project not found']);
}
$companies = $project->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
An alternative would be findOrFail which throws a ModelNotFoundException. You could handle the exception globally or catch it inside the controller:
try {
$companies = Project::findOrFail($args['projectid'])->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
return Response::json(['message' => 'Project not found']);
}
You first have to test whether the returned object is actually not null. Blindly assuming a database query succeeds is waiting for sh*t to hit the fan.
public function returnTop($count = 6, $args = Array()) {
$project = Project::find($args['projectid']);
if($project) {
$companies = $project->companies()->whereHas('products', function($q) use($args) {
$q->whereIn('products.id', $args['products']);
})->with('products')->limit($count)->get();
return Response::json($companies);
}
else {
return; // .. your error or whatever
}
}
Also the "call to a member function on a non-object" is quite specific, it tells you that a method (member function) could not be called due to the fact that you are trying to call it on a non-object.

Setting a table name in a model?

Im trying to pass in a table name to my model, as the model operates on two tables, but has the same methods.
I do it like so:
$this->model = new Emotions(array('section' => 'red'));
And in the model I set the table like:
public function __construct($attributes = array(), $exists = false){
parent::__construct($attributes, $exists);
$this->table = $attributes['section'];
}
But I get the error:
Undefined index: section
Any ideas where I'm going wrong?
Yes i get it, This class maybe running twice.
Please try this.
public function __construct($attributes = array(), $exists = false){
parent::__construct($attributes, $exists);
if(isset($attributes['section'])) {
$this->table = $attributes['section'];
}
}
My personal suggestion
<?php
class Emotions extends Eloquent
{
public function setTableName($name)
{
$this->table = $name;
return $this;
}
}
And you can use like this
$emotion = new Emotions(array('foo' => 'bar'))
->setTableName('blabla')
->save();
add below line to your class.
protected $fillable = array('section');
http://laravel.com/docs/eloquent#mass-assignment

Resources