Laravel how to get id parameter in model relation? - laravel

I've got a query to get messages:
public function getMessagesFor($id)
{
$messages = Message::where(function($q) use ($id) {
$q->where('from', auth()->id());
$q->where('to', $id);
})->orWhere(function($q) use ($id) {
$q->where('from', $id);
$q->where('to', auth()->id());
})->get();
}
and this logic works as it should, no errors all is ok. Now I want to get messages directly via model relatioship with other user (not authenticated one)
so in User model I wrote:
public function messages()
{
return $this->hasMany(Message::class, 'to', 'id')
->where('messages.from', auth()->id());
}
And this basically gives the same result as first where clause in getMessages function. This relatioship works ok.
The problem is that I don't know how to code the second part of where clause. I don't have access to $id in my model so how should I approach to this? Any ideas how to code it?
edit: message migration:
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->integer('from')->unsigned();
$table->integer('to')->unsigned();
$table->boolean('read')->default(false);
$table->integer('offer_id')->nullable();
$table->mediumText('body')->nullable();
$table->timestamps();
});

So I think the problem is the model relationship (user) is already set to get message where the user is the message reciever(to),
$this->hasMany(Message::class, 'to', 'id')
so you need to define another relationship to get messages where the user is the sender (from), so you have this
//user is reciever
public function sentMessages() {
return $this->hasMany(Message::class, 'to', 'id')
->where('messages.from', auth()->id()); }
//user is sender
public function recievedMessages() {
return $this->hasMany(Message::class, 'from', 'id')
->where('messages.to', auth()->id()); }
Anyway I advise you go with your first approach.
Okay, so adding your final soultion to get messages
//get all messages with
$this->sentMessages->merge($this->recievedMessages)

Related

Laravel : How to add conditional clause on a model having Many to Many model relationship?

I have this method on my User Model.
public function reviews()
{
return $this->belongsToMany(Review::class, 'review_user')->withTimestamps();
}
and its inverse here at Review Model.
public function reviewers()
{
return $this->belongsToMany(User::class, 'review_user')->withTimestamps();
}
They are connected via a pivot table review_user with following structure.
$table->id();
// User ID
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')
->references('id')
->on('users');
// Review ID
$table->unsignedBigInteger('review_id')->nullable();
$table->foreign('review_id')
->references('id')
->on('reviews');
$table->timestamps();
The review model has a boolean column status.
What I want is a users all reviews which has a status of true?
I have been able to achieve users all reviews using Auth::user()->reviews()->get();
How can I add a where clause, which can filter by status column ?
You can achieve this by using scope or Defining same Relationship with Extra Where Clause
Using Relation:
public function Activereviews()
{
return $this->belongsToMany(Review::class, 'review_user')
->whereStatus(true)
->withTimestamps();
}
OR Using Scope:
public function scopeActivereviews()
{
return $this->reviews()
->whereStatus(true);
}
Now you can do:
Auth::user()->ActiveReviews()->get();
Hope it helps.
Thanks
Try this code like that, does works
$reviews = auth()->user()->whereHas('reviews', function ($query) {
return $query->where('status', '=', true);
})->get();
And you check the official documentation
like option use documentation
Like all other relationship types, you may call the roles method to continue chaining query constraints onto the relationship:
$roles = App\User::find(1)->roles()->orderBy('name')->get();

i am trying to rate user but user only able to rate himself

There are two users in my users table user1 and user2
the user2 wants to rate user1
i have created a Rating table
which is as
Schema::create('ratings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('rating')->nullable();
$table->string('review')->nullable();
$table->integer('rated_user_id');
$table->timestamps();
});
i have also created a model named Rating and defined a realtionship to the user
such as
public function user()
{
return$this->hasMany(User::class);
}
the code in my user model is as follow
public function Rating()
{
return $this->hasOne(Rating::class);
}
the code inside Ratingcontroller store function is as follow
public function store(Request $request)
{
//
$rating = new Rating;
$rating->fill($request->all());
$rating->user_id = Auth::id();
$rating->save();
return redirect()->back();
}
the problem is that in the rating table
every things looks fine
user_id is getting the id who is trying to post comment
and rated_user_id is givving the id to which the user is giving rating too
but the user is only able to rate himself not other users ..
The image in db is correct and Your store method in RatingsController is also works as expected.
So You want from us to give You code example to ProfileController method to get ratings provided by user and provided to user.
1) You've to add to User model following relation:
public function ratingsProvidedByMe()
{
return $this->hasMany(Rating::class, 'user_id', 'id');
}
public function ratingsProvidedToMe()
{
return $this->hasMany(Rating::class, 'rated_user_id', 'id')
}
2) in Rating model:
public function ratedBy()
{
return $this->belongsTo(User::class, 'user_id');
}
public function ratedTo()
{
return $this->belongsTo(User::class, 'rated_user_id');
}
3) in Your ProfileController:
public function view(Request $request)
{
$ratingsProvidedByMe =
Rating::with('ratedTo')
->where('user_id', Auth::id())
->all();
$ratingsProvidedToMe =
Rating::with('ratedBy')
->where('rated_user_id', Auth::id())
->all();
$me = $user = Auth::user();
return view(
'profiles.view',
compact(
'ratingsProvidedByMe',
'ratingsProvidedToMe',
'user', 'me'
)
);
}
P.S. it's just an example, adapt my example to Your project Yourself.

Order on second degree relationship in Eloquent

I have two models in a many-to-many relationship: Fixture and Event.
Fixture:
public function events()
{
return $this->belongsToMany(Event::class, 'fixture_events')->withPivot('player_id');
}
Event:
public function fixtures()
{
return $this->belongsToMany(Fixture::class, 'fixture_events')->withPivot('player_id');
}
You will notice that the pivot table has an additional field player_id. This is because FixtureEvent also had a relationship to a model called Player.
FixtureEvent:
public function fixture()
{
return $this->hasOne(Fixture::class, 'id', 'fixture_id');
}
public function event()
{
return $this->hasOne(Event::class, 'id', 'event_id');
}
public function player()
{
return $this->belongsTo(Player::class, 'id', 'player_id');
}
And Player has:
public function events()
{
return $this->hasMany(FixtureEvent::class);
}
My problem arises when I want to get all the fixture_events for a player and sort them by a field in the events table. This field is named sequence.
However, whatever I do, the events always come out ordered by ID.
This is the query that I would like to order by events.sequence, whether by using some type of join or whatever works (this is inside the Player model so $this is a player object):
$events = $this->events()->whereHas('fixture', function ($query) use ($round, $competition_id) {
$query->where('fixtures.round', '=', $round)->where('competition_id', $competition_id);
})->get();
I've tried adding a join query here on fixture_events.event_id = events.id and then ordering by events.sequence but this doesn't work.
I've also tried adding orderBy directly in the model relationship, i.e. in the Fixture model:
public function events()
{
return $this->belongsToMany(Event::class, 'fixture_events')->orderBy('sequence')->withPivot('player_id');
}
But this does nothing for my problem.
How do I make this happen?
Update
At first I misread the relations, can you try with the below query?
$events = $this->events()->whereHas('fixture', function ($query) use ($round, $competition_id) {
$query->where('fixtures.round', '=', $round)->where('competition_id', $competition_id);
})->with(['events.event' => function ($query) {
$query->orderBy('sequence');
}])->get();
You have a couple of alternatives, but first I suggest you to edit your relationship to include the sequence field you are trying to load.
Then proceed with one of the following:
Order by on the relationship definition, but I think you have to load that field from the pivot table, otherwise you won't have its value, and prefix the relations table on the orderby field.
public function events() {
return $this->belongsToMany(Event::class, 'fixture_events')
->withPivot(['player_id', 'sequence'])
->orderBy('fixture_events.sequence');
}
or with:
public function events() {
return $this->belongsToMany(Event::class, 'fixture_events')
->withPivot(['player_id', 'sequence'])
->orderBy('pivot_sequence');
}
Order by a pivot field outside the relation can be done like this:
$events = $this->events()->whereHas('fixture', function ($query) use ($round, $competition_id) {
$query->where('fixtures.round', '=', $round)->where('competition_id', $competition_id);
})->with(['fixture' => function ($query) {
$query->orderBy('sequence');
}])->get();
or with:
$events = $this->events()->whereHas('fixture', function ($query) use ($round, $competition_id) {
$query->where('fixtures.round', '=', $round)->where('competition_id', $competition_id);
})
->orderBy('pivot_sequence')
->get();
Let me know if any of these methods works!

How to get weekly and monthly report in laravel?

I want to get weekly reports and monthly reports on my application, but I don't know where to start.
I use Laravel 5.7, I have tried a number of experiments that I have searched for on the internet, but they don't work.
My table
Schema::create('surat_keluars', function (Blueprint $table) {
$table->increments('id');
$table->string('nomor_surat')->unique();
$table->integer('instansi_id')->unsigned();
$table->string('perihal');
$table->date('tanggal_surat');
$table->date('tanggal_kirim');
$table->string('lampiran');
$table->timestamps();
$table->foreign('instansi_id')->references('id')->on('instansis');
});
My model
class SuratKeluar extends Model
{
protected $fillable = [
'nomor_surat', 'instansi_id', 'perihal', 'tanggal_surat', 'tanggal_kirim', 'lampiran'
];
public function instansi()
{
return $this->belongsTo('App\Instansi');
}
}
And and I have tried using this controller, but I don't know how to display it in view blade
public function day()
{
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m');
});
}
I hope someone can help me.
based on your question if you want to show it in view you can return the controller to the view like this:
public function day(){
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m')});;
return view('name_of_the_view')->with('name_of_variable_in_view', $data);
}
please make sure the $data variable is the data for your report by using var_dump like this
public function day(){
$data= SuratKeluar::select('id', 'nomor_surat', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('m')});;
var_dump($data);
}
and please ensure that you already build the view for your review you can read the documentation in here https://laravel.com/docs/5.7/views

How can i create dynamic delete method in laravel?

in codeigniter i can set method for dynamic delete like this code.in laravel how can i set this method for dynamic delete method.Thanks
in controller function
public function Delete($id)
{
if ($this->process_model->DynamicDelete($id, "interest_statement")) {
//
}
}
in model function
public function DynamicDelete($id, $table)
{
$this->db->delete($table, ['id' => $id]);
return TRUE;
}
you can use route as like below:
Route::get('yourroute/{info}','Yourcontrolller#Yourmethod');
and use this route in view page where from request get:
{{ URL::to('/yourroute/'.$id.'&your_table')}}
and finally you write a function in your controller
public function Yourmethod($info){
$explode=explode('&',$info);
DB::table($explode[1])->where('id',$explode[0])->delete();
Session::flash('flash_message', 'Your Data Delete Successfully');
return back();
}
Thank you
In Laravel, you can use Raw Query (Database: Query Builder)
Example:
Table: users
Condition: votes > 100
DB::table('users')->where('votes', '>', 100)->delete();
In your case:
public function DynamicDelete($id, $table) {
return DB::table($table)->where('id', '=', $id)->delete();
}

Resources