I currently have a form/view that allows a User to save an Order. This also updates a pivot table with the respective Products and qtys. What I am trying to do, is after this information is inputted and saved into the database, I want to send the user to a checkout page that shows all the information they inputted for that Order.
Relationships
User hasMany Order
Order belongsToMany Product
Product belongsToMany Order
checkout.blade.php
#foreach ($orders as $order)
#foreach ($order->products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->pivot->qty }}</td>
</tr>
#endforeach
#endforeach
OrderController.php
public function checkout($id)
{
$user = Auth::user();
$user->load("orders.products"); //eager load pivot table
$orders = $user->orders->where('order_id', $id);
return view('orders.checkout', compact('orders', 'user'));
}
I know I am calling the order incorrectly, because if I change
$orders = $user->orders->where('order_id', $id);
to
$orders = $user->orders;
It displays correctly, except of course, it populates with every Order's detail.
Or is there some elegant way for me to pass the data from the checkout function without this additional query? (I understand about moving data in Sessions, but I am working with a pivot table, and that complicates things.
If on the checkout page, you want to use just the latest order that the user has made, then you can just load that order using route model binding
Route::get('checkout/{order}', 'OrdersController#checkout');
Then in your controller:
public function checkout(Order $order)
so from here, you can pass this order to the view, and list all the products from this order, and also in your Order model you should have a reference to the user that this order belongs to:
public function user()
{
return $this->belongsTo(User::class);
}
Accessing columns from the pivot table will be:
#foreach($order->products as $product)
<div> {{ $product->pivot->column }} </div>
#endforeach
Related
I am trying to delete a record within a table using Laravel. I've tried many different things.
I have the following in my view:
#foreach($providers as $provider)
<tr>
<td>{{$provider->{'Provider First Name'} }}</td>
<td>{{$provider->{'Provider Last Name (Legal Name)'} }}</td>
<td>{{$provider->{'Provider Credential Text'} }}</td>
<td>Link </td>
<form action="/blah/{{$provider->NPI}}" method="POST">
{{ csrf_field() }}
<td><button type="submit"> Delete </button> </td>
</form>
#endforeach
I have the following in my routes:
Route::post('/blah/{id}', function($id) {
//Get user id for currently logged in user
$user = Auth::id();
//Query UserToProviderMappings table to get record where provider is mapped to user
$query = DB::table('user_to_provider_mappings')
->where('user_id', $user)
->where('provider_npi', $id)
->delete();
// $query->delete();
// return back();
});;
The view works fine. When I click delete in the view, I get redirected to a search results page and the record is not deleted in the table. I did try both post and delete in the route/form.
The search results page I am being redirected to has the following route:
Route::resource ('search-results', 'SearchResultsController');
And the following in the SearchResultsController:
public function index()
{
{
//The search() function is accessed using 'scopeSearch' within NPIData Model
$providers = NPIData::search()->orderBy('NPI')->paginate(20);
return view('inc.searchresults', compact('providers'));
}
You are using Query Builder not Eloquent so you are not dealing with Models, so there is no delete method to be calling on anything that could be returned. You are also calling get which returns many results not 1 result.
Since you are using Query Builder you should just replace get() with delete() to do a DELETE query to remove the record(s).
It is entirely possible you are not deleting anything at all though. You should check the result of the delete().
Actually I want to relationship with two tables one is the student table where some data of a student. another table has department notice. I want to access the department notice according to the student department. The student has login id, password, dept & much other information of an individual student on the student table. The screenshot is given below
Now I want to try to access according to the dept. Another Table dept. the screenshot is given below.
Here given the CseDepartment model
public function administration()
{
return $this->belongsTo('App\Administration','dept');
}
Administration model
public function department()
{
return $this->hasMany('App\CseDepartment','dept');
}
function is given below
public function individualdepartment(){
$this->AdminAuthCheck();
$id=Session::get('id');
$student=Administration::find($id);
return view('Student.department',compact('student'));
}
view page department
#foreach ($student as $students)
{{-- expr --}}
<tr>
<td>{{$students->department->name}}</td>
<td>{{$students->department->message}}</td>
<td></td>
<td></td>
<td></td>
</tr>
#endforeach
In your controller, you are calling the find() method, which gives you one object, a student.
$student=Administration::find($id);
In your blade page, you are then asking to loop on that single object and produce a collection:
#foreach ($student as $students) // There is only ONE student, this will not loop.
If you want the above to work, you can grab a collection from your controller:
// Note the plural naming convention to make it a little more clear
$students=Administration::all();
return view('Student.department',compact('students'));
Then in your blade file, you can loop like this:
#foreach ($students as $student) // note the name plural --> singluar
<tr>
<td>{{$student->department->name}}</td> // Now you have a single student
<td>{{$student->department->message}}</td>
This will resolve the non-object error.
I have orders table, and for each user weekly payments table.
I want to show user that he wil take total payment count on depending week.
I have created the query but on blade side, when i try to access other tables via eloquent it gives does not exits in this collection.
If i dont use group by function it works. But with group by function it doent
$earnings = user()->orders()->where('payment_status',0)-
>where('status',1)->get()->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('W');
});
In blade side my codes like following;
#foreach($earnings as $earning)
<tr>
<td>{{$earning->user->name}}</td>
<td>{{$earning->order->commission}}</td>
<td>{{$earning->user->bank}}</td>
<td>{{$earning->user->iban}}</td>
<td>{{$earning->user->phone}}</td>
#endforeach
get() should be last:
$earnings = user()->orders()
->where('payment_status',0)
->where('status',1)
->groupBy('created_at')
->get();
How about using DATE_FORMAT function:
$earnings = user()->orders()
->where('payment_status',0)
->where('status',1)
->groupBy(DB::raw("DATE_FORMAT(created_at, '%W')"))
->get();
Assuming your table is orders, you can do like this:
$earnings = user()->orders()->select('orders.*', DB::raw("DATE_FORMAT(created_at, '%W') as week"))
->where('payment_status',0)
->where('status',1)
->get()->groupBy('week');
Laravel Collection groupBy() function returns a collection of grouped collections.
$earningGroups = user()->orders()
->where('payment_status',0)
->where('status',1)
->get()
->groupBy(function($earning) {
return Carbon::parse($earning->created_at)->format('W');
});
Now this is a collection of earning groups, not earnings.
#foreach($earningGroups as $earcningGroupName => $earcningGroup)
// So here you have a group or earnings
// I don't know why did you want to group.
// For an example I will print the group name as a table row here.
// But do whatever you want.
<tr>
<td>{{ $earningGroupName }}</td>
</tr>
// So if you want to loop through earnings, you have to loop again.
#foreach($earningGroup as $earning)
<tr>
<td>{{$earning->user->name}}</td>
<td>{{$earning->order->commission}}</td>
<td>{{$earning->user->bank}}</td>
<td>{{$earning->user->iban}}</td>
<td>{{$earning->user->phone}}</td>
</tr>
#endforeach
#endforeach
I have 2 tables which are user and customer, The first table has the following fields: (id, name, email, password)
Then, the table customer has the following fields: (id, name, firstname).
In my Controller Customer, via my function index(), I have to retrieve id_user from my table user.
Question 1: Is my relationship correct between my 2 tables?
Model Customer
protected $fillable = ['name', 'firstname', 'user_id'];
public function user()
{
return $this->belongsTo('App\User');
}
Model User
public function customers()
{
return $this->hasOne('App\Customer');
}
Question 2: How do I retrieve ID of the user who is connected ?
I have for now this only...
public function index()
{
$customers = Customer::orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Question 3: I want to understand the two answers, but I would also like to understand how I can adapt my file index.blade.php via my loop, please.
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
Thank you for your explanations.
Your models are good. If you want to return user relation for every customer you should try like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
And in your view you should have:
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
<td> {{$customer->user->id}}</td>
More about that here.
Question 1: Is my relationship correct between my 2 tables?
Yes, your relationship is correct.
Explanation:
For your customer table, you indicate that a customer profile belongs to one and only one user. This is an inverse one-to-one entity relationship.
For your user table, you indicate that a user has one and only one customer profile. This is a one-to-one entity relationship.
Question 2: How do I retrieve ID of the user who is connected?
Use Laravel's Eager Loading by calling the with() method to retrieve the customer data with the associated user data like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Explanation:
The returned result can be visualized like this:
{Customer}
|
•id
•name
•firstname
•{user}
|
• id
• name
• email
Finally you can get the results including the user ID in your view like this:
#foreach($customers as $customer)
<tr>
<td>{{ $customer->user->id }}</td>
<td>{{ $customer->firstname }}</td>
<td>{{ $customer->name }</td>
</tr>
#endforeach
For more details on Laravel Entity Relationships see the relevant Laravel documentation.
I have a table of "rosters" that's pretty much strictly foreign keys. It acceses the "schools" table, "courses" table, and "students" table. So essentially, a 'student' takes a 'course' at a 'school'. My RostersController has this
public function show($id)
{
$roster = Roster::where('course_id', $id);
return view('roster')->with('roster', $roster);
}
My Roster Model is:
public function students()
{
return $this->hasMany('App\Student');
}
My student Model is:
public function roster()
{
return $this->belongsTo('App\Roster');
}
my view is this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>{{$child->students->first_name}}</p>
#endforeach
The rosters table just saves the student_id rather than all of the student's data that is already in the 'students' table. So i'm trying to access the students table from this relation but when i run this, it tells me that anything related to the students table is 'not on this collection'. I know that I could do things this way if i was working with a hasOne relationship, but how can i accomplish this with a hasMany to output the students table value in each row?
You should try this
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id);
return view('roster')->with('roster', $roster);
}
Try this
Roster.php
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id)->get(); // load the students
return view('roster')->with('roster', $roster);
}
On the view
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>
<!-- Loop through the stundents since this returns an collection of students and not just one -->
#foreach($child->students as $student)
{{$student->first_name}} <br>
#endforeach
</p>
#endforeach
Check this for more information on eager loading
The $child->students is a collection. So, you need to use another foreach loop inside the first one.
Your code should look like this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
#foreach($child->students as $student)
<p>{{$student->first_name}}</p>
<p>{{$student->age}}</p>
<p>{{$sutdent->another_column_in_students_table}}</p>
#endforeach
<p>{{$child->any_other_column_in_roster_table_if_needed}}</p>
#endforeach
So, your first issue is, that
$roster = Roster::where('course_id', $id);
will just return a QueryBuilder instance, you have to use
$roster = Roster::where('course_id', $id)->get();
then for sure, students is a collection, you have to iterate over it like this:
#foreach ($child->students as $student)
{{ $student->yourProperty}} <br>
#endforeach
Update:
I saw you know already about that when to use get() in query laravel 5