How to pass parameters between controller methods - laravel

I am having problems getting the value of custom create method. What I want is to get the variable $student_id and place it on my findOrFail() in the index method as shown below:
ReservationController.php
public function index()
{
$student = Student::with(['sectionSubjects','sectionSubjects.section',
'sectionSubjects.subject'])->findOrFail(1); //$student_id
return $student->sectionSubjects;
}
public function create($id)
{
$student_id = $id;
$subjects = Subject::with('sections')->get();
return view('reservation.form',compact('subjects','student_id'));
}
Here's my route:
Route::resource('student', 'StudentController');
Route::resource('reservation', 'ReservationController', ['except' => ['create','show'] ]);
Route::get('reservation/{id}/create',
['as' => 'reservation.create', 'uses' => 'ReservationController#create'
]);
I have this form.blade.php that when a user click on a student it will be redirected to the custom create method in the ReservationController as seen below:
<div class="list-group ">
#inject('student', 'App\Http\Controllers\StudentController')
#foreach($student->index() as $s)
<div class="list-group-item">
<h4 class="list-group-item-heading">
{{ $s->first_name }} {{ $s->middle_name }} {{ $s->last_name }}</i>
</h4>
<h5>
ID No.: {{ $s->id_no }}</i>
</h5>
Edit Info
<a href="{{ route('reservation.create', $s->id ) }}"
class="btn btn-xs btn-danger">
Enroll
</a>
</div>
#endforeach
</div>
Now in the index method in the ReservationController, I want to fetch only values that are related to that $student_id. However, I cannot figure out to achieve this. Can anyone suggest ways to solve this?

Actually you don't have any problem expect Logic problem.
Your Controller not designed in the correct way.
You need to have something like this
//List all subjects
public function index() {
return view('reservation.form')->with('subjects', Subject::with('sections')->get());
}
//List a single subject
//If i didn't misunderstood you, you can remove this one according to the source code you're using.
public function show($id) {
return view('reservation.oneSubject')->with('subject', Subject::find($id));
}
//Enroll a student to subject
public function enroll($id, $student_id) {
//Find the section for $id
//Add student_id to that section
}
And you need to define one extra route could be GET or POST in this example i'm using GET
Route::get('/reservation/{id}/enroll/{student_id}', 'ReservationsController#enroll');
What logic should i follow?
List all subjects (will call index())
Select one subject (will call show($id))
Show students.
Click add button (will call enroll($id, $student_id)
How do i pass $id, $student_id to enroll?
Your reservations resource will have these routes.
/reservations
/reservations/{id}/store
etc..
id parameter in your example, Pointing to Subject not Student.
Let's say you've a show($id) function which will show single subject and list of students,
return view(...)->with('subject', Subject::find($id)->with('students', YOUR_STUDENTS);
In the view, iterate through students, assuming you've $students
#foreach($students as $student)
Enroll student
#endforeach
I don't have show() function!
Since you don't have a show function that will display single subject, Same logic will apply here,
Iterate through subjects
Display subject
Iterate throught students
Generate anchor tags as the example above
So you'll have something like this,
#foreach($subjects as $subject)
<h1>{{ $subject->title }}</h1>
#foreach($students as $student)
<div class="students">
<h2> {{ $student->name }}</h2>
Enroll
</div>
#endforeach
#endforeach

Related

i am trying to show single data but it is showing" Trying to get property 'id' of non-object"

**after clicking "read more" i want to show a single post**
<a href="{{ URL::to('single/blog/'.$post->id) }}" class="btn btn-primary
float-right">Read More →</a>
** **the route is****
Route::get('single/blog/{id}','Web\Site\HomeController#show');
**the controller is**
public function show($id)
{
$posts = Post::findOrFail($id);
return view('site.home.singleblog',compact('posts'));
}
****the single section is****
#foreach($posts as $post)
<img class="img-responsive" src="{{asset("uploads/posts/$post->id/image/$post->image") }}" alt=""
{{ $post->name }}
{{$post->description}}
#endforeach
Your variable $posts is a single Post instance from Post::findOrFail($id) (where $id is coming from a route parameter, so a single value). You don't want to be iterating an instance of a Model. Use it in your view like a single model instance not a collection.
public function show($id)
{
view('site.home.singleblog', [
'post' => Post::findOrFail($id),
]);
}
Then in the view just remove the #foreach and #endforeach.
Try this:
{{ $post['name'] }} {{$post['description']}}
If you fetched $posts successfully, it should work. The error says $post is not an object but you are using object syntax to get value by key. So use array syntax.

Undefined variable: foods

hi guys am in need of assistance , i know this seems to be an easy one but am a bit confused , i have a foreach loop in my main.blade.php file, which shows foods from my database it works fine but when its clicked it meant to lead to the individual post and thats where i get the error
Undefined variable: foods
heres my foreach loop in main.blade.php file
#foreach($foods as $food)
<li class="item">
<a href="{{ route('Foods.show', $food->id) }}">
<img src="{{ Storage::disk('local')->url('food_images/'.$food->image ) }}" class="img-responsive w-25 p-3" alt="Food" >
<div class="menu-desc text-center">
<span>
<h3> {{ $food->title }}</h3>
{{ $food->body }}
</span>
</div>
</a>
<h2 class="white"> #{{ $food->price }}</h2>
</li>
#endforeach
heres my main.blade.php controller
public function LoadHome()
{
$foods = Food::all();
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home')->withFood($foods);
}
and heres Foods.show controller function
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->withFood($foods);
}
please what am i doing wrong
Have you tried passing data from your controller to the view using this something like this:
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->with('foods', $foods);
}
or, if you're passing multiple variables to the view:
public function show($id)
{
$foods = Food::Find($id);
$something = "else";
return view('foods.show', compact('foods', 'something'));
}
Your view doesn't know what $foods is at that point, so it's always good practice to check that foods is set before the loop:
#if (isset($foods) && $foods->count() > 0)
#foreach($foods as $food)
...
#endforeach
#endif
See the official Laravel docs for more information.
If you want the variable to be named foods in the view then you would need to use withFoods not withFood:
return view(...)->withFoods($foods);
As mentioned in the other answers, there are other ways to pass data to the views as well.
There is no data being passed to a view.
This is how you pass data to a view:
public function LoadHome()
{
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home', ['foods' => $foods])
}
If you always want to have $foods in main.blade.php you should place this in a service provider
View::share('foods', Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get());
https://laravel.com/docs/7.x/views#sharing-data-with-all-views

Stuck on many to many to many data call for an uni Assignment

I have an assessment I am not having an easy time of. I keep getting stuck on very small stuff. Im a 3d artist learning to code. So the part I am currently stuck on (small part of quite a large assignment) is I have a home page that lists restaurants like a food portal similar to like uber eats. Clicking on those restaurants is meant to load up a specific menu to the restaurant. But I can't seem to get this working. The database has 10 menu items per restaurant ID and 5 Restaurants in total. I am using sqlite3 as the database with seeder data'.
Ive had many errors but the latest is "Call to undefined relationship [menus] on model [App\Menu]."
Any help is appreciated, Ive already wasted so much time on seeder issues and now getting stuck on this part feels so trivial compared to the rest of the assignment :(
Hopefully I have provided enough information. Thanks!
Routes page:
Auth::routes();
Route::resource('/', 'HomeController');
#Route::resource('show', 'MenuController');
Route::resource('main', 'HomeController');
Route::get('show/{id}', 'MenuController#show')->name("show");
Main blade
<p>
#foreach($restaurants as $restaurant)
<a href="{{ route('show', $restaurant->id) }}">
<ul>
<li>
{{ $restaurant->name }}
</li>
</ul>
</a>
#endforeach
</p>
Show.blade
#extends('layouts.app')
#section('title')
Home Page
#endsection
#section('content')
#foreach($menus->menu as $menu)
<td>
{{ $menu->id }}
</td>
#endforeach
users.php
public function restaurant(){
return $this->hasMany(Menu::class,'App\Restaurant');
}
Restaurant.php - Model
public function user(){
return $this->belongsToMany('App\User');
}
Menu.php - Model
public function user(){
return $this->belongsToMany(User::class, 'menus_id');
}
Home Controller
public function index()
{
$restaurants = Restaurant::all();
return view('home', compact('restaurants'));
//return view('home')->with('restaurants', $restaurants);
}
Menu Controller
public function index()
{
$menus = Menu::all();
return View::make('show', compact('menus'));
}
public function show($id)
{
$menus = Menu::find($id)
->with('menus')
->where('id', $id)
->first();
return view('menu.show', compact('menus'));
}

Laravel Eloquent Query works on controller but Blade also fails

There are two models,
User
id, name, surname, email, etc.
Comment
id, user_id, comment, etc.
Comment Model
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
I can get the user's email address when I try the controller with the following query
$comments = Comment::where('status',1)->orderBy('id', 'desc')->take(5)->get();
foreach ($comments as $comment){
return $comment->user->email;
}
However, what I did not succeeded, I get an error when I write the following to the Blade file.
#foreach($comments as $comment)
<a href="{{ $comment->user->email }}">
<img class="avatar" src="{{ $comment->user->photo }}"
data-at2x="{{ $comment->user->photo }}"
alt="{{ $comment->user->slug}}">
</a>
#endforeach
Error Message : Trying to get property of non-object
I am waiting for your help, thanks in advance.
you can do this using Lazy Eager with
$comments = Comment::with('user')->where('status',1)->orderBy('id', 'desc')->take(5)->get();
return view('YourViewPath/ViewFileName.blade.php',compact('comments'));
now in your view:
#foreach($comments as $comment)
<a href="{{ $comment->user->email }}">
<img class="avatar" src="{{ $comment->user->photo }}"
data-at2x="{{ $comment->user->photo }}"
alt="{{ $comment->user->slug}}">
</a>
#endforeach
In your comment Model add with field
class Comment extends Model
{
protected $with = [
'user'
];
protected $fillable = [
....
];
public function user (){
return $this->belongsTo('App\User' ,'user_id' ,'id' );
}
}
Try with a condition.
#foreach($comments as $comment)
<a href="{{ $comment->user->email?$comment->user->email:'' }}">
<img class="avatar"
src="{{ $comment->user->photo?$comment->user->photo }}"
data-at2x="{{ $comment->user->photo }}"
alt="{{ $comment->user->slug?$comment->user->slug:''}}">
</a>
#endforeach
I found the reason for your frustration. More precisely, at http://forum.laravel.gen.tr/viewtopic.php?pid=12477#p12477 #mgsmus replied to my friend.
Briefly, I need to explain; Some commenters are not in the user table.
Suggested 2 ways to Prevent this.
First;
If you are getting a try-to-get property of a non-object error, then one of the comments does not have a record associated with any User model, ie one of them is null.
In such cases you can use the optional () helper function. (Laravel is available in 5.5 and 5.6 but can also be easily passed into 5.4.) The optional () helper function allows the property to return null if the object is null, without error, instead of a non-object error.
https://laravel.com/docs/5.6/helpers#method-optional
So instead of $ comment-> user-> email in the blade, type optional ($ comment-> user) -> email. Others are optional ($ comment-> news) -> link and optional (optional ($ comment-> exam) -> link, so you will see which record is not linked.
The other way is to only keep records that have only an association:
https://laravel.com/docs/5.6/eloquent-relationships (Querying Relationship Existence section)
// has ('user') to make sure that we have 5 comments with the User.
// This is different from whereNotNull ('user_id') because it checks whether the has model really is. user_id may be full but we do not know it is a User with id.
Comment :: has ('user') -> where ('check', 1) -> orderBy ('id', 'desc') -> take (5) -> get ();

laravel display data on a page based on id

I have a page that shows links with name of businesses that are retrieved in database like this:
Controller:
public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}
View:
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
#foreach ($business as $businesses)
<a target="_blank" href="{{ url('business/' . $businesses->name) }}"> {{($businesses->name) }}
</a> #endforeach
#endsection
Route:
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.
Controller:
function displayBusiness() {
$business = Business::all();
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
View:
#foreach ($business as $businesses)
<p>{{$businesses->name}}</p>
<p>{{$businesses->email}}</p>
#endforeach
#foreach ($address as $addresses)
<p>{{$addresses->firstline_address}}</p>
<p>{{$addresses->secondline_address}}</p>
<p>{{$addresses->town}}</p>
<p>{{$addresses->city}}</p>
<p>{{$addresses->postcode}}</p>
<p>{{$addresses->telephone}}</p>
#endforeach
Route:
Route::get('business/{name}', 'BusinessController#displayBusiness')->name('displayBusiness');
Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.
Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.
Thanks!
I do not know if I understood the question, but that may be the beginning of a solution ...
First view :
#extends('master') #section('title', 'Live Oldham')
#section('content')
#foreach ($business as $businesses)
<a target="_blank" href="{{ url('business/' . $businesses->id) }}"> {{($businesses->name) }}
</a> #endforeach
#endsection
Second Controller :
function displayBusiness($id) {
$business = Business::find($id);
$address = Address::find($id);
return view('displayBusiness', compact('business', 'address'));
}
Second View :
<p>{{$business->name}}</p>
<p>{{$business->email}}</p>
<p>{{$address->firstline_address}}</p>
<p>{{$address->secondline_address}}</p>
<p>{{$address->town}}</p>
<p>{{$address->city}}</p>
<p>{{$address->postcode}}</p>
<p>{{$address->telephone}}</p>
Second Route :
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');
Route parameters are available in the controller function as parameters. Now you can build a query with this function. If your query does not return any results, you can send the user back to the business overview.
function displayBusiness($name) {
$business = Business::where('name', $name)->orWhere('id', $name)->first();
if ($business === null)
{
// No business with this name or id found.
// Redirect to businesses list page.
}
$address = Address::all();
return view('displayBusiness', ['business' => $business, 'address' => $address]);
}

Resources