how to insert multiple data into a single column into the database - laravel

Am learning laravel and I encountered a problem saving data into my database from my form.
My instance
when a user tries to make a multiple purchase of products ie.when a user purchases more than one product,i wanted to save the names of products that belongs to the purchase user made into my 'PURCHASES' table having an 'ID' of '1'.
Names of product to be save;
1.productA
2.productB
3.productC
Codes
FORM IN MY VIEW
<input type='hidden' name='product_name'
#foreach($order as $order)
value='{{$order->product_name}}'
#endforeach >
MY purchase CONTROLLER
Saving the names;
$purchase = new Purchase;
$purchase->product_name = $posted['product_name'];
$purchase->save();
When i initiate the function i get an error exception reading 'Trying to get property of non-object' from my view from the line;
#foreach($order as $order)
value='{{$order- >product_name}}'
#endforeach >
How do i go about this problem?

There are a lot of strange things in your code unless I'm reading it wrong, but most likely when you're seeing that error in a view it's because you didn't pass that data into the view. Take this example:
Controller
public function showProducts() {
// assuming $order_array is a set of product IDs that is part of an order
$orders = array('products' => Products::whereIn('id', $order_array);
return View::make('your/view' compact('orders'));
}
I don't quite understand what you're trying to do but passing the object array 'orders' to the view allows you to then call your line:
#foreach($orders as $order)
code here
#endforeach

Related

Laravel Monthly Wise Data Access

Hi I want to show my database data as monthly wise so I create a query with groupBy() function.
When I try
#foreach($report as $date=>$data)
{{$date}}
#endforeach
I got the month name
March
May
But when I want to get data as monthly wise I try
#foreach($report as$data)
{{$data->fiscal_year}}
#endforeach
I got
Property [fiscal_year] does not exist on this collection instance. (View: C:\xampp\htdocs\report-management\resources\views\adcr\report\rent_certificate.blade.php)
I don't understand how can I access the data in monthly wise
This is my controller
public function RentCertificate(){
$data['report'] = Report::get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y-m');
});
return view('adcr.report.rent_certificate', $data);
}

ManytoMany relations in Laravel, retrieve data from related tables and display in blade

I have two tables related by many to many relation in Laravel Framework. I can display data from each table separately, but not through relation by taking one record from the 1st table and checking related records in the 2nd table. In tinker it accesses data fine.
Relations:
public function underperformances() {
return $this->belongsToMany(Underperformance::Class);
}
...
public function procedures() {
return $this->belongsToMany(Procedure::class);
}
My resource controller part:
...
use App\Underperformance;
use App\Procedure;
...
public function index()
{
$books = Underperformance::orderBy('id','desc')->paginate(9);
$procedures = Procedure::all();
return view('underpcon.underps', compact('books', 'procedures'));
}
Route:
Route::get('/underps', 'UnderpsController#index');
If I try to display data like this:
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances}}</li>
#endforeach
I get such format to the browser:
[{"id":1,"title":"Spare part not taken before service","description":"tekstas","level":"1","costs":600 ...
This is correct data from related table, but I cannot select further the specific column from that table. For example this does not work:
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances->id}}</li>
#endforeach
Nor this one:
#foreach ($procedures->underperformances as $underperformance)
<li>{{$underperformance->id}}</li>
#endforeach
How do I select records of the related table and display specific data from that table?
What would be a conventional way to do this?
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances->id}}</li>
#endforeach
^ This right there $procedure->underperformances will return a collection, not a single item, so you need to treat it as array, you will not be able to access the id directly, you can either #foreach that, or use the pluck method in Laravel Collections.

How to retrieve data with composite primary key in Laravel

I am working with four tables in Laravel and trying to display data to a view. I believe I am stuck because one of the tables has a composite primary key.
I have the following in my controller:
public function show($id)
{
//Get application for drug
$application = PharmaApplication::where('ApplNo', $id)->first();
//Return all products for application
$drugs = $application->products;
return view('profiles.drug', compact('drugs'));
}
I have the following in my PharmaApplication model:
public function products()
{
return $this->hasMany('App\PharmaProduct', 'ApplNo', 'ApplNo');
}
I have the following in my view (which I cannot complete)
#foreach ($drugs as $drug)
<li>{{$drug->Strength}}</li>
<li>{{$drug->Form}}</li>
<li>{{$drug->Form}}</li>
#endforeach
I am trying to accomplish the following:
Get the application for a drug - this part of my code works
Return an array of objects for the products (i.e. 7 products that belong to one application). I can do this but get stuck going to the next part.
Next, I have to use the array of objects and search a table with the following columns: MarketingStatusID, ApplNo, ProductNo. I know how to query this table and get one row using DB Query, but then how do I get the proper result to that query within the for loop in my view?
Finally, I use the MarketingStatusID to retrieve the MarketingStatusDescription which I will know how to do.

Laravel eloquent relationship between two table

I have a table notices. Model for this table is Notice.php
In this table I have notice and id column.
I have fetched all notices from notices table and viewed in my view. Here is my controller code for fetching all notices.
public function index()
{
$notice = Notice::orderBy('id','desc')->paginate(5);
return view('teacher.notice')->withNotices($notice));
}
Here is my view code to show all notices.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
#endforeach
Now I want to put two button inside this foreach loop. One is to confirm and another is remove confirmation.
To store this confirmation data I have created another table named notice_confirmed_student and model for this table is noticeConfirmedStudent.php. In this table have three column:
id
student_id
notice_id
If a student click confirm then his id and notice id will be stored in this table. I have done this perfect. But my problem is, in the foreach loop it shows both two button (confirm and remove confirm) at a time. I want to show confirm button if user already not confirmed for this notice. If user already confirmed for that notice then it should show remove confirmation button.
Here I am giving my blade foreach loop again with button for better understanding. Bellow code is not perfect, I have just written those code to understand my question.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
<?php $student_id= "select student_id from notice_confirmed_student where notice_id=$notice->id"; ?>
#if ($student_id == $auth::user()->id)
<button>confirm</button>
#else
<button>Remove Confirmation</button>
#endif
#endforeach
Thanks in advance.
Few things are wrong/incorrect here, to make it clear,
Notice <> User relation is Many-Many and notice_confirmed_student is a pivot table. so user model should have relation,
public function confirmedNotices()
{
return $this->belongsToMany(Notice::class, 'notice_confirmed_student')
}
Then in for each loop you can check like,
if(in_array($notice-id, Auth::user()->confirmedNotices->pluck('id')->all())) {
// user confirmed
} else {
// user not confirmed.
}
if I correctly understand your issue, you need to check if record with given id exists notice_confirmed_student table, and then check in your loop. retrieve the confirmed students with your notices.
$notice = Notice::with('notice_confirmed_student_or_whatever_your_relation_method_called)')->orderBy('id','desc')->paginate(5);
then check in loop, if related attribute is not empty like you do in your view
#if($notice->my_attr && $notice->my_attr->user_id == \Auth::user()->id)
// do stuff
#else
// it doesn't has record
#endif

Laravel 4 Eloquent Problems Select with hasMany Relation

I have 2 models : Album & Photo.
Album hasMany Photo and photo belongsTo('album','id');
Just Like:
class Photo extends Eloquent {
protected $table = 'photo';
public function album(){
return $this->belongsTo('album','id');
}}
and
class Album extends Eloquent {
protected $table = 'album';
public function photo()
{
return $this->hasMany('photo');
}}
i have no problem until i want to try select Album Name and show first photo on an Album.
I am trying this code:
<?php $albums= Album::get();?>
#foreach($albums as $album)
<pre>{{$photo = $album->photo->first()}}</pre>
#endforeach
and output :
{"id":1,"images":"1.png","album_id":1,"created_at":"2014-09-08 03:54:36","updated_at":"2014-09-08 03:54:36"}
{"id":3,"images":"3.jpg","album_id":3,"created_at":"2014-09-08 04:30:35","updated_at":"2014-09-08 04:30:35"}
it's mean i have 2 album and i already select first photo of each album.
and when i trying to call images attributes it's error:
echo "$album->photo->first()->images";
error :
It is likely that you have an Album in your database which does not have a Photo associated with it. So when you loop over your albums and echo {{ $album->photo->first() }}, it simply outputs null for any album that does not have a photo (because there is, obviously, no first()) without throwing an error. However, when you try to access the image property of the album that doesn't have a photo, you are trying to get a property of a non-object, i.e. you are asking for the image property of null. Hence an error is thrown.
You can resolve this by wrapping your output in an #if statement that checks to make sure a photo exists, before trying to access its image property:
#foreach($albums as $album)
#if (count($album->photo))
{{ $album->photo->first()->image }}
#endif
#endforeach
There is a shortcut for this, using blade's or syntax, which checks for existence before trying to echo the result. This allows you to remove the #if statement:
#foreach($albums as $album)
{{ $album->photo->first()->id or null }}
#endforeach
First of all, I would recommend when using Eloquent to retrieve all entries in a table, use ::all() instead of ::get(), as shown in Basic Usage. Not sure if it's causing the problem, but you may want to follow the docs.
Secondly, in relationship, the first parameter to hasMany and belongsTo should be the model class name. So it should be 'Album' and 'Photo', first letter capitalized.
Judging from you output, album_id seems to be the foreign key name. So in your Photo class, change the relationship into the following:
public function album(){
return $this->belongsTo('Album','album_id');
}
Just ran your code, the issue is that you did not define the primary key for you models. Laravel will assume you are using 'id' as the primary key, and if that's not the case, your relationship will break. And it's always better to explicitly define what the primary key is, so as to avoid confusion when foreign keys are involved. So please add to the model class:
protected $primaryKey = 'album_id';
You can revise your code and see if the error persists. It's not showing up in my end now.

Resources