Why doesn't laravel recognize my model? - php

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.

Related

Laravel 5.4 - Model accessor not working

I´ve been trying to make an accessor work a few hours now, to no avail. I have simplified my model code to the bare bones, and still no luck.
Here´s the code in PersonaIdentificacion.php:`
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PersonaIdentificacion extends Modelo
{
public $table = "personaidentificacion";
public function getFooAttribute() {
return 1;
}
}`
I use Artisan Tinker to try and retrieve the value of the 'foo' property, but I only get: 'null'. I don´t get it. What am I missing??
Your getFooAttribute() is fine.
To your model add the following assuming that it's a new attribute
protected $appends=['foo'];
and then you can call
$id = App\PersonaIdentificacion::first(); $id->foo;
This should work fine.

use QueryScope in Blade template

I have define scope in model like this
class Station extends Model {
protected $primaryKey = 'st_id';
public function scopeByDid($query)
{
return $query->groupBy("st_did");
}
}
I can call byDid from controller but I cannot get it through blade template like this
#foreach ($river->stations->byDid as $didType)
....
#endforeach
how do I get it. Appreciate your response. Thanks
If you're getting a relationship as an attribute (without () at the end) it means the relationship will have already been retrieved before the scope.
To get your code to work you will just need to change your foreach to:
#foreach($river->stations()->byDid()->get() as $didType)
Hope this helps!

laravel eloquent orm view

My ultimate goal is to print the contents of a table in a database to a table in HTML using Laravel's ORM.
Beyond that I know how to configure the database file, but is there any other things i need to configure.
From my understanding I need three files. Do i need to make a controller? If so how does that work?
Item Class
Route.php
views.php
Here is what I have so far
Item.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model {
protected $table = 'items';
protected $primaryKey = 'item_id';
public function products()
{
return $this->belongsTo('item_id', 'item_name', 'item_cost');
}
}
routes.php
<?php
Route::get('Product', function()
{
$products = \App\items::all();
return view('Items', $items);
});
and I have no idea how to create a view in HTML.
I know I'm completely off at this point, but I've read the documentation and I am still completely lost when they reference things like URI and have URL in the same sentence without defining or even linking to it elsewhere in the documentation.
Actually, you have declared your Eloquent ORM like this:
class Item extends Model {
// ...
}
But you are using that model/class like this:
$products = \App\items::all();
In this case, \App\items doesn't exist, it should be:
$items = \App\Item::all(); // <-- Item not items
return view('items', $items); // <-- $items not $products
You asked: Do i need to make a controller?
In this case, no, it'll work fine with the anonymous function but using a Controller is better for many reasons.
Update:
Create a view in resources/views as items.blade.php and you can print out the items through a foreach loop. Check the documentation.

Laravel 5 mutators only work when I create a record and not when I update a record

Hi I have created a mutator to only store digits on my phone numbers. Here is my code in my Profile Model.
public function setPhoneAttribute($phone)
{
$this->attributes['phone'] = preg_replace("/[^0-9]/","",$phone);
}
This works when I create a new record, but if I update the record it does not work. My question is how do I execute the Mutator on both create and update?
Here is how I update and create in my controller:
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Requests\ProfileRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Profile;
class ProfileController extends Controller {
public function create(ProfileRequest $request)
{
// Check if the user does not have a profile yet
if(!Auth::user()->profile()->first()){
// Save to database
$saveToDatabase = Auth::user()->profile()->create($request->all());
return $saveToDatabase;
}
}
public function update(Profile $profile, ProfileRequest $request)
{
// Save to database
$saveToDatabase = Auth::user()->profile()->update($request->all());
return $saveToDatabase;
}
}
Here's what's happening:
Auth::user()->profile()->create($request->all()) calls the create method on your relationship (HasOneOrMany). This method then creates a new instance of the related model. This is important because obviously attribute mutators are only used when the record is created through the model.
However the relationship object doesn't have any update method. (It also wouldn't make sense to have one...). So what's happening instead is, when you do Auth::user()->profile()->update($request->all()). The update call get's proxied off to a query builder instance (that matches the relationship). This results in something like this being executed:
UPDATE profiles SET foo = 'bar' WHERE [relationship conditions]
It doesn't use the model at all. Therefore the mutator doesn't work.
Instead you have to call the update method on the actual related model. You can access it by just calling the relation as a property like this:
$saveToDatabase = Auth::user()->profile->update($request->all());
// ^^
// no parentheses
If the Profile model is injected correctly you actually might also just use that though:
public function update(Profile $profile, ProfileRequest $request)
{
// Save to database
$saveToDatabase = $profile->update($request->all());
return $saveToDatabase;
}
Using this code instead of your code
$saveToDatabase = Auth::user()->profile->update($request->all());

Undefined variable laravel 4.1

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

Categories