Laravel CRUD ORM Can't find model - php

I have been trying to associate a User with a Profile.
Here is my code:
Profile Model:
class Profile extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
User Model:
class User extends Authenticatable
{
...
public function profile(){
return $this->hasOne('App/Profile');
}
}
ProfileController:
public function show($username)
{
$user = User::where('username',$username)->first();
$profile = $user->profile;
return view('profiles.show')->withProfile($profile);
}
Route (It's meant to be "profil"):
Route::resource('profil','ProfileController');
Error:
http://prntscr.com/ff6y0a
Any tips on doing the rest of the CRUD functionality is very welcome!

Change App/Profile to App\Profile in your User model relationship.

Related

Problem with Laravel Eloquent - relation not working

I'am beginner in Laravel. I have project in Laravel 5.8.
I have User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use psCMS\Presenters\UserPresenter;
use scopeActiveTrait;
public static $roles = [];
public $dates = ['last_activity'];
// ...
public function scopeHistory()
{
return $this->hasMany('App\UserLoginHistory');
}
// ...
}
and UserLoginHistory:
class UserLoginHistory extends Model
{
protected $quarded = ['id'];
public $timestamps = false;
protected $fillable = ['user_id', 'date_time', 'ip'];
public function user()
{
return $this->belongsTo('App\User');
}
}
I want show user login history by this code:
User::history()->where('id', $idAdmin)->orderBy('id', 'desc')->paginate(25);
but it's not working.
This function not working - I haven't got results.
How can I fixed it?
First of all, you are defining your relationship as a scope (prefixing the relationship with the scope keyword). Try updating your model relationship to this:
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
Then, given your query, it seems that you want to get all the UserLoginHistory
records for a given User. You could accomplish this in two ways (at least).
From the UserLoginHistory model itself, constraining the query by the foreign key value:
$userId = auth()->id(); // get the user ID here.
$results = UserLoginHistory::where('user_id', $userId)->paginate(15);
// ^^^^^^^ your FK column name
From the User model using your defined relationship:
$userId = auth()->id(); // get the user ID here.
$results = User::find($userId)->history;
The downside of the second approach is that you'll need to paginate the results manually.
in your User model you should define your relation by this way :
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
then if you would like to select with history model you can do that with WhereHas() method :
User::whereHas(['history'=>function($q) use ($idAdmin) {
$q->where('id',$idAdmin)
}])->orderBy('id', 'desc')->paginate(25);
You must be do this changes
public function history()
{
return $this->hasMany('App\UserLoginHistory');
}
usage
$user = User::find($idAdmin);
$userHistories = $user->history()->latest()->paginate(25);
or get user with all history
User::with('history')->find($idAdmin);
// Post model
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
}
// Category model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}

Can't access to laravel hasone relation method from controller

I am struggling with the relation hasOne. here is what I have
User model:
class User extends Authenticatable
{
use Notifiable;
public function candidat()
{
return $this->hasOne('App\Model1');
}
public function element ()
{
return $this->hasOne('App\Model2');
}
}
Model1 class:
class Model1 extends Model
{
//
public function user()
{
return $this->belongsTo('App\User');
}
}
Model2 class:
class Model2 extends Model
{
//
public function user()
{
return $this->belongsTo('App\User');
}
}
Controller class:
public function savingcandidat(CandidatRequest $requete){
$candidat = $this->candidatSave($requete);
$user = User::query()->where('email',$requete->email)->get(); //there i get the user
//here is where i get the error : "Method Illuminate\Database\Eloquent\Collection::candidat does not exist."
$user->candidat()->save($candidat);
}
I get the error:
"Method Illuminate\Database\Eloquent\Collection::candidat does not
exist."
when I use tinker it works properly, thank you in advance for your help
$user = User::query()->where('email',$requete->email)->get();
This will return a collection result and it will not have that model/builder method. use first() instead of get if it's just one record
Like this
$user = User::query()->where('email',$requete->email)->first();

Class App not found error in (Laravel 5.4)

I want to insert the remark field into the database, but it seems that it doesn't work. So instead, I get the following error.
Class 'App\Job' not found
Jobs.php
class Job extends Model
{
public function index()
{
return view('create-job');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
JobController.php
class JobController extends Controller
{
public function postCreateJob(Request $request)
{
// Validation
$post = new Job();
$post->remarks = $request['remarks'];
$request->job()->save($post);
return redirect()->route('home');
}
public function index()
{
return view('create-job');
}
}
Your model name is Jobs.
Need to change the name of the model to Job
Hope this helps.

one-to-many relationship doesn't work

I am trying to create one-to-many relationship with 2 models, User and Role. So, I would like that one User can only have one role, and the Role can be assigned to more than User. I tried to follow the offical tutorial on https://laravel.com/docs/5.1/eloquent-relationships#one-to-many, and ended up with this:
class User extends Model
{
public function role()
{
return $this->belongsToMany('App\Admin\Role');
}
}
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\Admin\User');
}
}
Based on that link, I think the Role is the same thing as the Post, one Role can be assigned to many User. However, this doesn't quite work, here is how I tried to access the role name for a specific User
$role_first = $user->role; // Eloquent\Collection
$role_second = $user->role(); // Eloquent\Relations\BelongsToMany
$role_first->role_title // 'Undefined property: Illuminate\Database\Eloquent\Collection::$role_title'
$role_second->role_title // exception 'ErrorException' with message 'Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$role_title'
What is exactly wrong here?
In the User class
public function role()
{
// not $this->belongsToMany('App\Admin\Role');
return $this->belongsTo('App\Admin\Role');
}
Because you want a oneToMany not manyToMany relationship.
This should do it. Please give it a try
class User extends Model
{
public function role()
{
return $this->hasOne(App\Admin\Role::class);
}
}
// user belongs to one role
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->belongsTo(App\Admin\User::class);
}
}
User Model
class User extends Authenticatable{
public function roles(){
return $this->belongsTo('App\Admin\Role');
}
}
Role Model
class Role extends Model{
public function users(){
return $this->hasMany('App\Admin\User');
}
}
The user can have only one role, and the role can be assigned to many users.
Just make sure the relation
A User hasOne Role
A Role belongsToMany Users
so, in this condition
class User extends Model
{
public function role()
{
return $this->hasOne('App\Admin\Role');
}
}
class Role extends Model
{
protected $table = 'roles';
public function users()
{
return $this->belongsToMany('App\Admin\User');
}
}
and must check your user_id foreign constraint be 'unsigned' in your role migration table.

Laravel: hasMany() with take() only working on first result

I have the following models.
class User extends Eloquent {
public function comments() {
return $this->hasMany('Comment');
}
}
class Comment extends Eloquent {
public function user() {
return $this->belongsTo('User');
}
}
For the sake of this example, a user could have 1,000s of comments. I am trying to limit them to just the first 10. I have tried doing it in the User model via
class User extends Eloquent {
public function comments() {
return $this->hasMany('Comment')->take(10);
}
}
and via UserController via closures
$users = User::where('post_id', $post_id)->with([
'comments' => function($q) {
$q->take(10);
}
]);
Both methods seem to only work on the first record of the result. Is there a better way to handle this?

Categories