I am trying to get data from database and pass values to controller. I am new at laravel and thats the first query. Here is my code:
class Cars extends Eloquent
{
}
FleetController.php
public function index()
{
$fleet = Cars::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
{{ $fleet }}
#stop
The problem is that it shows this at log
Next exception 'ErrorException' with message
'Undefined variable: fleet (View: C:\wamp\www\laravel\app\views\pages\home.blade.php)' in C:\wamp\www\laravel\app\storage\views\7da5cff457f71f3156f90053865b6cb1:2
Stack trace:
You should try using
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
Your '->with()' just flashes the variable to your session. You still need to retrieve it from there though.
Also, you should try creating a model with the same name as your table. If you were to create a model Car that extends Eloquent, it will automatically be linked to your Cars table. Laravel docs:
The lower-case, plural name of the class will be used as the table
name unless another name is explicitly specified.
This part is important as well:
Eloquent will also assume that each table has a primary key column
named 'id'.
Once you got that configured, you'll be able to get the description of a car by simple doing
Car::all()->first()->description;
See also: Laravel docs on eloquent
Update
What should work:
Car.php
class Car extends Eloquent{
//Let's try setting these manually. Make sure they are correct.
protected $table = 'cars';
protected primaryKey = 'id';
}
FleetController.php
public function index()
{
//You have to call the model here, so singular 'Car'.
$fleet = Car::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
//You can use blade's #if as well:
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
#stop
Related
I would like to known how to get data from database in blade like from User table:
{{ Auth::user()->name }}
I have table user_settings
I would like to get record from this table by logged user id like this:
{{ UserSettings::user()->my_field }}
How can I do that?
Try this on your blade view
{{ \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field }}
In default, model file is inside App folder.
Such direct access to database table is not preferred though, you can return this as a variable from controller function like,
$field = \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field;
return view('view_name',comapact('field'));
and use in blade like
{{$field}}
Another good way is posted by Orkhan in another answer using eloquent relationship.
Hope you understand.
You need to retrieve the UserSettings associated to the authenticated user:
UserSettings::where('user_id', Auth::id())->first()->my_field
You can defined a method named current() to return that for you.
class UserSettings extends Model
{
public static function current()
{
return UserSettings::where('user_id', Auth::id())->first()
}
}
Then use:
UserSettings::current()
On the other had it would better to use one-to-one relationship on user model:
class User extends Model
{
public function settings()
{
return $this->hasOne('App\UserSettings');
}
}
Then use:
Auth::user()->settings->my_field
I get this error that says, "No query results for the model [App\dummy]." I believe the problem is in the controller. When you submit the form it is supposed to trigger the function in the comment controller. This controller is new so, I believe the error is in here. That is when it stopped working. Here is the commentController file:
<?php
namespace App\Http\Controllers;
use App\Dummy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; //this one is for sql builders
use App\Comments;
use Illuminate\Http\RedirectResponse;
use DateTime; //to create a new date object you need to include this namespace
class commentController extends Controller
{
public function store(Dummy $post){
$date = new DateTime();
$timestamp = $date->getTimestamp();
$id = $post->id;
$post->addComment(request('body'));
return view('post', compact('post', 'timestamp', 'id'));
}
}
I tried making App\Dummy lowercase so it was App\dummy but still it didn't work. It still gives me the error.
Here is my dummy model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class dummy extends Model
{
protected $guarded = [];
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
public function addComment($body){
$this->comments()->create(compact('body'));
}
}
Your error is that your class is called dummy buy you are using it as Dummy, so rename it both (file and class) to Dummy.
This class dummy extends Model to this class Dummy extends Model.
Remember that your file should be called Dummy.php too, not dummy.php
Change your model class name to Dummy and file name to Dummy.php.
Your main problem here is the route model binding. When you're trying to add a comment, the $post object is not getting resolved based on your route. You have bad a route setup or trying to add comment to a non existent post.
Basically the error message No query results for the model happens because of this code that the route model binding does for you.
$post = Dummy::findOrFail($id);
Try changing this
Route::post('post/{dummy}/comments', 'commentController#store');
public function store(Dummy $dummy)
The problem was in the form. The action attribute in the form was something like this:
<form class="col s12" action={{ url('/post/$id/comments') }} method="post">
I thought that would get the id because I compacted the id into the variable $id. But then I checked the url and noticed not a number but the actual word $id. So, here is the solution:
<form class="col s12" action={{ url('/post/' . $post->id . '/comments') }} method="post">
Just to let you guys know that when it said, "No query results for the model [App\dummy]." It meant that when I used this method from the dummy model which had this line of code:
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
It couldn't find the primary key from the dummies table. Therefore couldn't connect with the foreign key which is the post_id from the comments table. So, it wasn't able to submit the new comment to the table for that unique blog post. This is the last part that submits the comment to the table:
public function addComment($body, $name){
$this->comments()->create(compact('body', 'name'));
}
by the way comments() is the method I created that i just showed before.
Conclusion
It pretty much stopped working in the web.php file(routing file) because it wasn't getting an id. Due to the mistake I made in the action attribute in the form that i explained before.
I have two tables in my database - vnames and vtypes
vtypes have a name field and a id field, vnames have a id field, name field and a vtypes_id field which is a foreign key connected field. It is connected with the id field in vtypes.
I have Vname and Vtype models -
Vname
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vname extends Model
{
public function vtype() {
return $this->belongsTo('App\Vtype');
}
}
Vtype
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vtype extends Model
{
public function vname() {
return $this->hasMany('App\Vtype');
}
}
When i delete any column in vtype table i want to delete all the vname columns associated with it.
I found a solution like this -
public function vtypeDestroy($id) {
$vtype = Vtype::find($id);
$vtype->vname()->detach();
$vtype->delete();
Session::flash('success', 'The vtype was successfully deleted');
return redirect('/vtypes');
}
but when i run this function i get an error like this - Call to undefined method Illuminate\Database\Query\Builder::detach()
How can i fix it?
And when i want to get the name of the vtype from vname i am not able to do it. I tried like this
#foreach ($vnames as $vname)
{{ $vname->vtype()->name }}
#endforeach
in a view
But i got an error like this -- Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
Please guide me how to fix this two problems which i face now.
Your relation should be as:
Vname Model
class Vname extends Model
{
public function vtype() {
return $this->belongsTo('App\Vtype', 'vtypes_id', 'id');
}
}
Vtype
class Vtype extends Model
{
public function vname() {
return $this->hasMany('App\Vname', 'vtypes_id', 'id');
}
}
Then you can use delete method to delete the relations as:
$vtype = Vtype::find($id);
$vtype->vname()->delete();
$vtype->delete();
And in your view it should be as:
#foreach ($vnames as $vname)
{{ $vname->vtype->name }}
#endforeach
Docs
Please use...
$vtype->vname()->delete();
instead of $vtype->vname()->detach();... Problem solved! For the inverse of it, vname->vtype() you can you dissociate() method... which will set vtype_id to null in vname table. More explanation here
Detach is used for belongsToMany() - belongsToMany() relation... yours is hasMany() - belongsTo().
Also, instead of doing {{ $vname->vtype()->name }}
please do
#foreach ($vnames as $vname)
{{ $vname->vtype->name }}
#endforeach
The reason for this is... when you put the brackets in front of the relation name, it calls a query builder... But here, what you need is the model... So $vname->vtype will give you Vtype Model while $vname->vtype() will give you query builder.
I have 2 tables, tn_project has id name cv_id_project and tn_activity has id name id, i want to get the name of the project which is cv_project_name rather its id.
Basically when i click add activity i have select option to choose which project that i use, i manage to get the id of selected project but i want its name(i can select up to 3 project in a single activity)
Model
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'tn_activity';
public $timestamps = false;
public function projectModel(){
return $this->hasMany('Activity\Project','cv_id_project','id');
}
}
VIEW
#foreach($query as $result)
<td>{{$result->projectModel->cv_project_name}}</td>
#endforeach
Controller
public function index(){
return view('landing-page')
->with('title','Landing Page')
->with('query',Activity::with('projectModel')->get())
->with('projects',Project::all());
}
usually it's work but i don't know what makes it error
and then this error occured
Undefined property: Illuminate\Database\Eloquent\Collection::$cv_project_name (View: C:\xampp\htdocs\PKL\netxcel-2-backup2\resources\views\landing-page.blade.php)
Your Activity projectModel is a collection, because it has hasMany relationship. If it's really true, you should get the project name like this.
#foreach ($result->projectModel as $project)
<td>{{$project->cv_project_name}}</td>
#endforeach
However, if it shouldn't have hasMany relationship than you should change the hasMany part
I have a laravel fetching controller like below,
public function fetchbywhere()
{
$result=User::find(2);
return View::make('fetchbywhere')->with('resultrow',$result);
}
My Model file of User.php like,
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
and my routes.php file ,
Route::get('select-by-where',array('as'=>'select_by_where','uses'=>'Test#fetchbywhere'));
and my view file named fetchbywhere.blade.php,
<title>Fetch by Where clouse</title>
<h2>Users - Where clouse</h2>
#foreach($resultrow as $data)
<ul>
<li>{{$data->name}}</li>
</ul>
#endforeach
my database have fields like
id|name|email|age|created_at|updated_at
am getting error like Trying to get property of non-object (View: E:\wamp\www\new_laravel\app\views\fetchbywhere.blade.php)
anybody please give me a solution. t
thanks
You are using User::find(2) this returns a single instance of User with id = 2. Or even null if it doesn't exist. In your view you are iterating over $resultrow as if it where a collection and not a single model.
I believe what you actually want to do is something like this:
$result=User::where('some-column', 'operator', 'some-value')->get();
return View::make('fetchbywhere')->with('resultrow',$result);
So an example could be...
$result=User::where('age', '>', '18')->get();
return View::make('fetchbywhere')->with('resultrow',$result);
...to get everybody over 18
Also its "where clause" not clouse ;)
Update
The actual use for the find method is to get only one object with the passed id (primary key in the database). It doesn't return a collection (list) because there no way it could find multiple rows with the same id, since the primary key is unique.
If you only want one user (by a specific id) you have to change your view to directly access the model
<title>Fetch by Where clouse</title>
<h2>Users - Where clouse</h2>
{{ $resultrow->name }}