I have Users_group model in my Laravel project.
Code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function getGroupData()
{
return $this->hasOne('App\Group','id','group_id');
}
}
And when I want to get data from this model I use this my custom method:
$data = App\Users_group ::get();
It's working great
I want to get the data from model with condition not like this:
$data = App\Users_group::where('group_id','>',5)->get();
I need to put the condition inside the model file thats make the model return the data everytime I call User_group::get() return it when condition inside the model.
Thanks!
You can use query scopes to achieve this. Query scopes allow you to add a global constraint to a model.
In your case, you could add the following boot method to your model:
protected static function boot()
{
parent::boot();
static::addGlobalScope('groupOver5', function (Builder $builder) {
$builder->where('group_id', '>', 5);
});
}
try this one in by using scope in model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function scopeGetGroupData($query,$value,$opertor = '>')
{
return $query->where('group_id', $opertor, $value);
}
}
get data in controller like this u can pass also parameter in method
App\Users_group::GetGroupData($value)->get();
Related
I, ve got problem with eloquent relationships.
This is my DB
https://i.stack.imgur.com/2we4g.jpg
https://i.stack.imgur.com/20KeG.jpg
I've got Santander ID in santander column in partner table and want to use data from those two table like from one
This is my Partner.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Partner extends Model
{
use HasFactory;
protected $table='partner';
protected $connection='mysql2';
protected $guarded = [];
public $primaryKey = 'id';
public function santander()
{
return $this->hasOne(Santander::class, 'id', 'santander');
}
}
This is my Santander.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Santander extends Model
{
use HasFactory;
protected $table='santander';
protected $connection='mysql2';
protected $guarded = [];
public $primaryKey = 'id';
public function partner()
{
return $this->belongsTo(Partner::class, 'id', 'santander');
}
}
In controller I use Eloquent collection like this:
use App\Models\Partner;
use App\Models\Santander;
$partners = Partner::paginate(10);
In view. I am using it like this:
#foreach partners as partner
{{ $partner->santander->operator }}
#endforeach
but it generates error:
Trying to get property 'santander' of non-object
First of all are you sure about the relationships itself?
$this->hasOne(Santander::class, 'id', 'santander');
The first extra argument should be the foreign key, so assuming that the related column in the model Santander is named santander then it should be:
$this->hasOne(Santander::class, 'santander', 'id');
(the specified id as last param can be omitted btw)
Same goes for the relationship in the other model.
Apologies if the title doesn't completely make sense... I wasn't sure if the exact terminology for the linking of models are the associated data in their controllers.
I'm trying to paginate a table with the posts created by a user.
I managed to paginate it previously, without the user_id in the posts table. But I've added the user_id to the posts table, and run the migration which works fine.
The following is my Post model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
And this is my User model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['name', 'email', 'password',];
protected $hidden = ['password', 'remember_token',];
public function posts() {
return $this->hasMany('App\Post');
}
}
And this is the relevant section of the post controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use Session;
use Carbon\Carbon;
class PostController extends Controller
{
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('posts.index')->with('posts', $user->posts);
}
I thought that it would simply be a case of appending ->paginate(5) to the $user in the PostController, but that doesn't appear to work.
I get the following:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I've tried including the {!! $posts->links() !!} in the posts.index view before the #foreach but that gives:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$posts
I'm trying to learn Laravel basics by creating this crud application, and have tried combining two tutorials together, but I'm clearly missing something.
You can call ->paginate() on the relationship like this (also I've removed the unnecessary user query, since auth()->user() will execute it already):
public function index()
{
$user = auth()->user();
$posts = $user->posts()->paginate();
// Or with 1 line: $posts = auth()->user()->posts()->paginate();
return view('posts.index')->with('posts', $posts);
}
I have a tw-tier nested hasOne relationship and the final relationship appears to be giving null values.
My JobApplication relationship has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobApplication extends Model
{
protected $table = 'job_applications';
protected $primaryKey = 'job_application_id';
public function jobrequest()
{
return $this->hasOne('App\Model\JobRequest', 'job_request_id', 'job_request_id');
}
}
My JobRequest Model has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobRequest extends Model
{
protected $table = 'job_requests';
protected $primaryKey = 'job_request_id';
public function jobgroup()
{
return $this->hasOne('App\Model\JobGroup', 'job_group_code', 'job_group_code');
}
public function jobapplication()
{
return $this->belongsTo('App\Model\JobApplication', 'job_request_id');
}
}
And my JobGroup has the following:
<?php
namespace App\Model;
use Carbon;
use Illuminate\Database\Eloquent\Model;
class JobGroup extends Model
{
protected $table = 'job_groups';
protected $primaryKey = 'job_group_code';
public function jobrequest()
{
return $this->belongsTo('App\Model\JobRequest', 'job_group_code');
}
}
I access them in my controller like so:
$job_applications = JobApplication::with(['jobrequest', 'jobrequest.jobgroup'])
->where('user_id', Auth::id())
->first();
It queries right on the Debugbar (and yes the query for job_groups gives out data), but when I dumped $job_applications, jobgroup shows null
Dont need to eager load it. I can access it like so
$job_applications = JobApplication::with('jobrequest')->where('user_id', Auth::id())->first();
dd($job_applications->jobrequest->jobgroup);
I get this error message if I try to run my post on postman:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::posts()
My routes Looks like this:
Route::middleware('auth:api')->group(function ()
{
Route::get('posts', ['as' => 'posts', 'uses' => 'Api\PostController#index']);
}
And the Controller like this:
class PostController extends Controller
{
public function index()
{
$posts = Auth::client()->posts()->get();
dd($posts);
return response()->json(['data' => $posts], 200, [], JSON_NUMERIC_CHECK);
}
}
My Client model:
class Client extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, HasApiTokens, Notifiable;
protected $table = 'clients';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function posts()
{
return $this->hasMany(Post::class);
}
}
And my Post model:
namespace App;
use App\Client;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function client()
{
return $this->belongsTo(Client::class);
}
}
If I dump this: $posts = Auth::user()->get();
I get an Output, but I want to get the post Output.
You should define the relationship first.
<?php
...
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
Once it has been defined, you can access the collection of posts by accessing the posts property. Most important, you should retrieve a single row firstly, then access the collection of posts like this:
$client = Client::find(1);
$posts = $client->posts;
Or you can serve the relationship as query builders like this:
$posts = App\Client::find(1)->posts()->where('name', 'tests')->get();
Iff it still occur the error, You should check if Auth::client()return client model instance.
dd(Auth::Client());
I'm not sure how you've defined Auth::client(), but judging by some of the code there is a misconception of how models are instantiated, and what get() does.
get() returns a collection of results.
Auth::user() already returns a user instance, when you call Auth::user()->get(), you are sending a second query to the database and returning a list of users.
$user->posts()->get() has a more conventional/memoized way of accessing the dataset, `$user->posts.
I'd recommend checking out your Auth::client() method and make sure you're not accidentally returning a new query.
I have a problem posting data in Laravel 5. I've done a page that post stuff on a controller that would create a new row on a database, according to Eloquent class. But when I post that, I receive a blank page and nothing works.
This is my controller, focused on the affected class:
<?php namespace App\Http\Controllers;
use App\T_subject;
use App\T_reservation;
use Date;
use Request;
use Config;
use Validator;
use Auth;
class TutoringController extends Controller {
public function reserve(Request $request)
{
$reservation = new T_reservation;
$reservation->user_id = Auth::user()->id;
$reservation->subject_code = $request->input('subject');
$reservation->date = $request->input('date');
$reservation->topic = $request->input('topic');
$reservation->save();
return redirect('/tutoring/view/'.$request->input('subject'));
}
}
This is my Eloquent model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class T_reservation extends Model {
protected $table = 't_reservations';
public function user()
{
return $this->belongsTo('App\User');
}
}
And my routes file:
<?php
Route::post('tutoring/reserve', ['middleware' => 'auth', 'uses' => 'TutoringController#reserve']);
Where's the problem?
In your routes file there is no definied route for your final redirection: '/tutoring/view/'.$request->input('subject').
Also, your model have no fillable property, which should list properties for which you can make a mass assignment. For instance something like this:
protected $fillable = ['user_id', 'subject_code', 'date', 'topic'];