Associate method in laravel 8 - api

I'm new to laravel and I'm making a small api with just two tables to start. I have roles and people. I want to assign a role to a person from the store method but I don't understand how associate() works or how to implement it in the store method, this is what i have;
Model Rol:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
protected $fillable = ['id', 'rol'];
public function personas()
{
return $this->hasMany(Persona::class);
}
}
Model Persona:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Role;
class Persona extends Model
{
use HasFactory;
protected $fillable = ['id', 'nombres', 'apellidos', 'rol_id'];
public function rol()
{
return $this->belongsTo(Role::class, 'rol_id');
}
}
$rol = Role::find(1);
$persona->rol()->associate($rol);
$persona->save();
Persona controller store method:
public function index()
{
return PersonaResource::collection(Persona::with('rol')->paginate(25));
}
public function store(Request $request)
{
//$rol = Role::find(1);
$persona = new Persona();
// datos que voy a guardar
$persona->nombres = $request->nombres;
$persona->apellidos = $request->apellidos;
$rol = new Role();
//$rol->personas()->save($rol);
$persona->rol()->save($rol);
}
I want to know how to correctly associate both models to be able to correctly save the related data

Related

Laravel: How to send value from Controller to Model?

How can I send a value from Controller to Model and how to receive the value in the Model.
I let above a picture of my database tables.
enter image description here
Example: If I enter in the input 3 action movies
$category=category::with('film')->where('name','=','Action')->first();
Film model:3
class film extends Model{
protected $table = "film"; //Para nao dar o erro de singular e plural
protected $primaryKey = 'film_id';
public $timestamps = false;
use HasFactory;
protected $sql=['film_id', 'title', 'release_year'];
public function category(){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
}
}
Category model:
class category extends Model{
protected $table = "category";
protected $primaryKey = 'category_id';
public $timestamps = false;
use HasFactory;
protected $sql=['category_id','name'];
public function film(){
return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
}
}
NOTE: I realized that I need to add in the front of the Category model
->take(3)
But I don't know how to send the value(3 or other else) via $category query.
You can simply put conditions in the closure of the "film" relationship on the controller to get 3 action movies or any number of movies.
Controller:
$limit = 3;
$category=category::with(['film'=>function($query)use($limit)
{
$query->limit($limt);
}])->where('name','=','Action')->first();
Controller Side
$category=category::with('film')->where('name','=','Action')->film->category($value);
Model Side
public function category($value){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id')->where('foo', $value);
}

notification system in Laravel 8

I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?

Property [client] does not exist on this collection instance

I can't get the value of the foreign key that is inside the booking table.
Booking Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class booking extends Model
{
protected $primaryKey = 'bookingID';
protected $fillable = ['clientID', 'checkInDate', 'checkOutDate', 'roomsCount', 'roomTypeID', 'adultsCount', 'childrenCount', 'amenityID', 'paymentID'];
public function client()
{
return $this->hasOne(Client::class,'clientID');
}
}
Client Table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class client extends Model
{
protected $primaryKey = 'clientID';
protected $fillable = ['fullNmae', 'firstName', 'lastName', 'phoneNumber', 'emailAddress'];
public function booking()
{
return $this->hasMany(Booking::class);
}
}
I tried adding the protected $primaryKey = 'bookingID'; and protected $primaryKey = 'clientID'; as suggested in my previous question but now I still can't get just the FirstName from the client table.
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
You are trying to get a property from a collection in these lines:
$bookingDetail = booking::with('client')->get();
return $bookingDetail->client->firstName;
but this property client is defined for object, not a collection. so to solve it you must take one object from the collection like the following:
$bookingDetail = booking::with('client')->first();
return $bookingDetail->client->firstName;
i thing you need to try this one:
in your booking model:
// 'App\Client' these is example you need to put your client model path
public function client()
{
return $this->belongsTo('App\Client','clientID');
}
in your client model:
public function booking()
{
return $this->hasMany('App\Booking' , 'clientID');
}

Creating queries in Paris ORM

I have a collection of Recipes and each one contains Categories. This are my models:
class Recipe extends \Model {
public static $_table = "recipe";
public function categories() {
return $this->has_many_through('Category');
}
}
class Category extends \Model {
public static $_table = "category";
public function categories() {
return $this->has_many_through('Recipe');
}
}
And the table to relate both:
class CategoryRecipe extends \Model {
public static $_table = "category_recipe";
}
Now I need to create a query to get all the Recipes that are under one/more categories. What is the way to achieve this? I want to avoid making things like this:
$results = $app['paris']->getModel('CategoryRecipe')
->where_in("category_id",$selected_categories)
->find_many();
foreach($results as $result) {
$recipe = $app['paris']->getModel('Recipe')
->where('id',$result->recipe_id)
->find_one();
var_dump($receta->name);
}
Create filters? functions inside the models? Is not possible to make it more elegant?
That is pretty much how I would do it, but you can optimise in one way. Add relation functions to your linking/many-to-many table. Then instead of doing that extra query in your foreach loop you simply do:
foreach($results as $result) {
$recipe = $result->recipe()->find_one();
var_dump($recipe)
}
So your CategoryRecipe model might look like:
class CategoryRecipe extends \Model {
public static $_table = "category_recipe";
public function recipe() {
$this->belongs_to('Recipe', 'recipe_id');
}
public function category() {
$this->belongs_to('Category', 'category_id');
}
}
I haven't tested this code, but it should be what you're after I think.

creation of model object in controller yii

can any one tell me how to create a model object inside a constructor in yii. I had written the code as belo
<?php
class DistributorsController extends Controller
{
public $layout = '//layouts/column4';
public $defaultAction = null;
public function __construct()
{
echo '<br>Into constructor';
parent::__construct('Distributors','distributors');
}
public function actionDistributors()
{
$this->render("ChannelMask");
}
}
?>
But it is displaying only "Into constructor" string and view is not showing in my browser.
You need to call a model into the Controller.
Create a model, then in Controller, call it like :
Distributor::model()->findAll($criteria); //many models
or
Distributor::model()->findById($id); // one model
Like any other place if you want to create a new model:
$model = new Distributors();
or
$model = $this->loadModel($id, 'Distributors');
if you want to populate your model with existing data, then:
$model = Distributor::model()->findAll(); // all there is
or
$model = Distributor::model()->findByPk($id); // find by primary key