I have a project in Laravel, where I want 2 values, resulted after post method from a form, to become global variables in all my views with special prefix.
My code in controller:
public function to_dashboard(UserLocationRequest $request)
{
$my_company_id = $request->my_company_id;
$my_branch_id = $request->my_branch_id;
View::share('my_company_id', $my_company_id);
View::share('my_branch_id', $my_branch_id);
return Redirect('employee/dashboard');
}
After this code I have errors:
'Undefined variable: my_company_id'
'Undefined variable: my_branch_id'
How can I do that, to propagate these 2 values in all my views?
Or how to send these values to my route.php and become global variables with View::share after submitting the form?
The way I will do it is using session in Laravel 5.
You put your values in session key Session::put('key', 'value'); like:
Session::put('my_company_id', $my_company_id);
Session::put('my_branch_id', $my_branch_id);
Then you can fetch the values from any where in Laravel:
$my_company_id = Session::get('my_company_id');
$my_branch_id = Session::get('my_branch_id');
I hope this cover your request.
I solved the problem with Session::set and Session::get:
public function to_dashboard(UserLocationRequest $request)
{
$my_company_id = $request->my_company_id;
$my_branch_id = $request->my_branch_id;
Session::set('my_company_id', $my_company_id);
Session::set('my_branch_id', $my_branch_id);
return Redirect('employee/dashboard');
}
In my view:
<ul class="dropdown-menu" role="menu">
<li>My Company: {{ App\MyCompany::find(Session::get('my_company_id'))->name }}</li>
<li>My Branch: {{ App\MyBranch::find(Session::get('my_branch_id'))->name }}</li>
<li>{{ Lang::get("site/menu.reset_password") }}</li>
</ul>
Related
I'm using laravel version 7.30.1. it shows the error undefined variable $services.
code for home controller.
class HelloController extends Controller
{
public function services()
{
$services = [
'service 1',
'service 2'
];
return view('/services',compact('services'));
}
}
code for blade file.
#section('content')
<H1>welcome to laravel 6 from services</H1>
<ul>
#forelse($services as $service)
<li>{{ $service }}</li>
#empty
<li>this list is empty</li>
#endforelse
</ul>
#endsection
code for route file
route::view('/services','services');
route::view('/services','services');
here your only loading view not controller that's why your data is not pass in to view
use get req. which will be in controller then form controller load view with data
Route::get('services',[\App\Http\Controllers\HelloController::class, 'services']);
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
I'm querying a model in a method in my controller to get all messages.
public function index(){
$messages = Message::where('sender_id', Auth::user()->id)->orWhere('recipient_id', Auth::user()->id)->get();
return view('/pages/message/index', compact('messages'));
}
If the model is null and has now entries, I get an error of 'can get method of non object or something like that.
What's the best way to handle errors like this. Ideallly in the controller
#if($messages)
//Codes
#endif
if collection in loop. Forelse statement is cool for that.
#forelse ($messages as $message)
<li>{{ $message->content }}</li>
#empty
<p>There is no messages</p>
#endforelse
in your view
#if(count($messages)>0)
//your code
#endif
or
#if(!empty($messages))
//your code
#endif
I am successfully getting results in/from my controller like this:
$session_id and $user_id are getting passed into my method.
Controller
// get all sets belonging to the user for the given session
$session = Session::findOrFail($session_id);
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id);
$user = User::findOrFail($user_id);
return View('users.index')
->with('session', $session)
->with('sets', $sets)
->with('user', $user);
View
<p>{{ $user->first_name }} has {{ $sets->count() }} existing set{{ ($sets->count() > 1 ? 's': '') }}.</p>
<ul class="list-unstyled">
#foreach ($sets as $set)
<li>
Set
</li>
#endforeach
</ul>
I am seeing "Foo has 1 existing set." and I can see the record in the DB. However, I'm not getting into the loop at all. If I add/remove records, my paragraph text updates accordingly as well - but I still never get into the loop to show each set. I'm sure it's something obvious, but I sure don't see it.
Thank you for any suggestions!
Change the query of sets to this:
$sets = Set::where('session_id', $session_id)->where('user_id', $user_id)->get();
As get() method will return you the collection object.
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