I am trying to make a drop down list in Laravel with the select options being values from my database and I have some issues. In other tutorials in this site, doing drop down list inquires building the models for your database. I have not created model classes and I do not intend to.
Routes.php
Route::get("/user/charname", array(
'as' => 'profile-character',
'uses' => 'ProfileController#dropDownList'
));
ProfileController.php
class ProfileController extends BaseController
{
public function dropDownList()
{
$list = DB::table('characters')->where('char_id', '128')->pluck('char_name');
return View::make('layout.profile')->with('character_options',$list);
}
}
In the profile.blade.php (view)
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="post">
<li>
{{ Form::select('character_options', $list ,Input::old('character_options')) }}
</li>
</form>
</div>
By doing this it says that $list from my view is undefined. Where do I define $list in the view and how will I carry $list from my Controller to the View because this line doesn't seem to do it's job
return View::make('layout.profile')->with('character_options',$list);
You need to use $character_options not $list in the View.
You actually specify that the variable should be 'character_options' in your View::make() call, so you need to refer to it as $character_options.
Additionally, ->lists('char_name') is better than using ->pluck('char_name') as it'll give you the full list. Pluck just returns the first item it finds.
Additionally to that, using ->lists('char_name', 'id') gets you the list keyed by the id column, which would be useful if you were to use this list to determine IDs for a foreign key field. But no biggie if not.
I have partially solved the issues by doing this in my view:
{{ Form::select('list', DB::table('characters')->where('char_id', '128')->lists('char_name') ,Input::old('list')) }}
Personally I do not see it as a viable solution, but a temporary one
{{ Form::select('character_options', $character_options ,Input::old('character_options')) }}
Error: undefined variable character_options
{{ Form::select('character_options', $list ,Input::old('character_options')) }}
Error: undefined variable list
Maybe I do not understand how i send the variable from the Controller to the View.
You need to use lists as mentioned by #alexrussel. Do note that View::make('layout.profile')->with('character_options',$list);, here you are passing the variable $character_options with the value contained in the $list and $list will no longer be available to the view.
ProfileController.php
<?php
class ProfileController extends BaseController
{
public function dropDownList()
{
$list = DB::table('characters')->where('char_id', '128')->lists('char_name');
return View::make('layout.profile')->with('character_options',$list);
}
}
profile.blade.php
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="post">
<li>
{{ Form::select('character_options', $character_options ,Input::old('character_options')) }}
</li>
</form>
Related
**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.
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
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 ();
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
I am having trouble figuring out why my data is not being posted and stored in my database. I have used the resource routes for another form and it works fine, but here for some reason it won't work. Clicking submit just seems to refresh the page, no errors to work from!
So I have a form which gets the workout routines from a database, and on submission I want this to create a new Workout "session" in my database table (called "Workouts"). The form is this:
{{ Form::open(array('url' => '/')) }}
<div class="form-group">
{{ Form::text('workout_name', Input::old('workout_name'), array('class' => 'form-control', 'placeholder' => 'Session Name')) }}
</div>
<div class="form-group">
{{ Form::select('routines', $routine_names, null, array('class' => 'form-control')) }}
</div>
{{ Form::submit('Select Routine', array('class' => 'btn btn-success pull-right')) }}
{{ Form::close() }}
In my HomeController I have this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Routine;
use App\Workout;
class HomeController extends Controller
{
public function index()
{
$routines = Routine::all();
$routine_names = Routine::lists('routine_name');
return view('workout')->with(array('routines'=>$routines, 'routine_names'=>$routine_names));
}
public function store()
{
$workout = new Workout;
$workout->workout_name = Input::get('workout_name');
$workout->save();
}
}
I have a model created for the Workout, and the route for this page is the following:
Route::resource('/', 'HomeController');
I can't figure out where I'm going wrong. The index method in my controller is working, as it is returning the correct view with the data I need. The form also looks OK I think, as I'm posting to the same page, but submitting doesn't seem to carry out the code I have in the store method of the HomeController.
Any help would be appreciated!
Thanks :)
Change your route declaration from:
Route::resource('/', 'HomeController');
To something like this:
Route::resource('/workout', 'WorkoutController');
If you are using the resources controller creator command of php artisan then all the specific routes are created for you. To see all listed routes you can type , php artisan routes. This will show you RESTFUL routes even for your POST method .
And also even you did not created the resources controller and did made the routes with manual way then you can create ,
Route::POST('/workout' , SomeController#post);
I am trying to say , you have to use the different POST method for the form submission .
Hope this will solve your problem . Thanks.