Creating a URL with a FK - laravel

I'm trying to create a url which reads www.localhost/forum/{slug}/thread={id} but im encountering problems. The {id} part is coming back as that is the thread id but the {slug} part i'm trying to retrieve through a foriegn key and get the issue.
Call to a member function forums() on null
here are my tables
Forum: id, name, slug, timestamps
Thread: id, name, forum_id, user_id
here is my relation on my thread model
public function forums(){
return $this->belongsTo('App\Forum');
}
and here is my code on my ThreadController
public function show($id, $slug)
{
//
$thread = Thread::find($id);
$thread->forums()->slug = $slug;
return view('forum.thread')->withThread($thread);
}
Any ideas on how i get the Forum's slug into the URL?

Because $thread = Thread::find($id) Didnt get any thread. You can can use findOrFiail function, or check does thread exist, and after that call forums().

Maybe try $thread->forums()->setAttribute('slug', $slug)

So it looks like id is not a route parameter.
your controller method should be
public function show($slug)
{
$thread = Thread::find(request()->input('id'));
$thread->forums()->slug = $slug;
return view('forum.thread')->withThread($thread);
}
either that or change your route

Related

How can add additional Attribute in my JSON response with dynamic value in laravel

In my app i have a Posts and a Reacts table both are connected with relationship.
In App user can react to a post(like or dislike) and for retrieve this i'm using this function :
public function feed()
{
$posts=Post::with('user')
->with('reacts')
->withCount('comments')
->orderBy('created_at', 'DESC')
->get();
return response()->json(["posts" => $posts]);
}
the response is:
i want to add one more field in Posts Object for isUserLiked and if the current authenticated user liked the post then value will be true or false for him something like this:
i can add a additional field but how can i set the value dynamically for that
this is what i am doing in my Post Model:
protected $appends = ['isUserLiked'];
public function getIsUserLikedAttribute($id)
{
$react=React::where('user_id',auth()->user()->id)->where('post_id',$id)->exists();
return $react;
}
this is returning false because i don't know any way to pass the arguments(Post id).
is there any better way i can get the desired response? Thanks!
public function getIsUserLikedAttribute($id)
{
return React::where('user_id',auth()->user()->id)->where('post_id',$this->id)->exists();
}
In your user model:
public function reacts(){
return $this->hasMany(React::class);
}
public function scopeReactOnPost($query, $post_id){
return $this->reacts()->where(function($query) use ($post_id){
$query->where('post_id',$post_id);
});
}
and in your controller:
$user->reactOnPost($post_id)->first();
or
$user->reactOnPost($post_id)->get()->count();
Will let you know if user had any reaction on the specified post.
and for adding this to your json output you can artisan make a resource for your post model. Laravel Resources

Getting ID from url and using it in CRUD controller laravel

I need to add orders to existing customers. From my customers.show view I use the following to visit the order form.
href="{{action('OrderController#create', $customer['id'])}}
The link of the page looks like:
/orders/create?2f10f8a0-30b9-11e8-8711-dd477b141226
I've been using the following route::get to no avail to be able to use this ID in my resource controller for Orders
Route::get('orders/create/{id}', 'OrderController#create');
Basically need to be able to to something along the lines of below to be able to show customer details while displaying the create order form as well but getting stuck on best way to pass the id through for the current customer
public function create(){
$customer = Customer::find($id)
return view('orders.create', compact('customer'));
}
With Laravel, you just need to add the parameters you specified in the route as function parameters, like below:
public function create($id){
$customer = Customer::find($id)
return view('orders.create', compact('customer'));
}
You are not passing the $id argument in the create function.
Change it to:
public function create( $id ){
$customer = Customer::find($id)
return view('orders.create', compact('customer'));
}

Laravel oneToMany accessor usage in eloquent and datatables

On my User model I have the following:
public function isOnline()
{
return $this->hasMany('App\Accounting', 'userid')->select('rtype')->latest('ts');
}
The accounting table has activity records and I'd like this to return the latest value for field 'rtype' for a userid when used.
In my controller I am doing the following:
$builder = App\User::query()
->select(...fields I want...)
->with('isOnline')
->ofType($realm);
return $datatables->eloquent($builder)
->addColumn('info', function ($user) {
return $user->isOnline;
}
})
However I don't get the value of 'rtype' for the users in the table and no errors.
It looks like you're not defining your relationship correctly. Your isOnline method creates a HasMany relation but runs the select method and then the latest method on it, which will end up returning a Builder object.
The correct approach is to only return the HasMany object from your method and it will be treated as a relation.
public function accounts()
{
return $this->hasMany('App\Accounting', 'userid');
}
Then if you want an isOnline helper method in your App\User class you can add one like this:
public function isOnline()
{
// This gives you a collection of \App\Accounting objects
$usersAccounts = $this->accounts;
// Do something with the user's accounts, e.g. grab the last "account"
$lastAccount = $usersAccounts->last();
if ($lastAccount) {
// If we found an account, return the rtype column
return $lastAccount->rtype;
}
// Return something else
return false;
}
Then in your controller you can eager load the relationship:
$users = User::with('accounts')->get(['field_one', 'field_two]);
Then you can do whatever you want with each App\User object, such as calling the isOnline method.
Edit
After some further digging, it seems to be the select on your relationship that is causing the problem. I did a similar thing in one of my own projects and found that no results were returned for my relation. Adding latest seemed to work alright though.
So you should remove the select part at very least in your relation definition. When you only want to retrieve certain fields when eager loading your relation you should be able to specify them when using with like this:
// Should bring back Accounting instances ONLY with rtype field present
User::with('accounts:rtype');
This is the case for Laravel 5.5 at least, I am not sure about previous versions. See here for more information, under the heading labelled Eager Loading Specific Columns
Thanks Jonathon
USER MODEL
public function accounting()
{
return $this->hasMany('App\Accounting', 'userid', 'userid');
}
public function isOnline()
{
$rtype = $this->accounting()
->latest('ts')
->limit(1)
->pluck('rtype')
->first();
if ($rtype == 'Alive') {
return true;
}
return false;
}
CONTROLLER
$builder = App\User::with('accounting:rtype')->ofType($filterRealm);
return $datatables->eloquent($builder)
->addColumn('info', function (App\User $user) {
/*
THIS HAS BEEN SUCCINCTLY TRIMMED TO BE AS RELEVANT AS POSSIBLE.
ARRAY IS USED AS OTHER VALUES ARE ADDED, JUST NOT SHOWN HERE
*/
$info[];
if ($user->isOnline()) {
$info[] = 'Online';
} else {
$info[] = 'Offline';
}
return implode(' ', $info);
})->make();

How do I automatically set model properties when retrieved from the db?

In my route I have:
$products = Product::where('category',$category)->get();
return $products[0]->x;
How can I set up my Product model so that the route returns abcd1234?
This is what I currently have in my model:
public function __construct(){
$this->x = 'abcd1234';
}
You need an accessor.
Add this to your Product model:
public function getXAttribute()
{
return 'abcd1234';
}
Access it with:
$product = Product::where('category', $category)->first();
return $product->x;
Having a 1 character attribute name may cause a problem though, id recommend changing the X to something with more than one character in camel case for the accessor.

codeigniter pass variable from controller to model

simple issue I presume.
My controller is getting the if to display from the url using $this->uri->segment(3). This will always be a single value. I am putting this in an array to pass to the model with:
$customerid = array(
'id' => $this->uri->segment(3)
);
The controller syntax is below:
function confirm_delete_customer()
{
$data['title']="Confirm Customer Deletion";
$customerid=array(
'id'=>$this->uri->segment(3)
);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete()){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
I am then trying to access this array value and pass it to my model to process. If I hard code the array into the model it works as per below syntax:
Model - Manual Syntax is:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', array('id'=>43));
return $query->result();
}
if I try replace this with the array from my controller it fails with error:
Undefined variable: customerid
idea of model that I want to get working:
function get_customer_records_to_delete()
{
$query = $this->db->get_where('customers', $customerid);
return $query->result();
}
I have a feeling it is something small. however is this the best way to get a single record from the database in order to output to a view?
Thanks in advance for the assistance.
The best way to do that is:
function confirm_delete_customer()
{
$data=array();
$data['title']="Confirm Customer Deletion";
$customerId = $this->uri->segment(3);
//Prevent SQL injections
if(!is_numeric($customerId) || empty($customerId)) {
show_error("Bad Request");
}
$query = $this->model_master_data->get_customer_records_to_delete($customerId);
if ($query){
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}
}
and then you can simply call:
function get_customer_records_to_delete($customerId)
{
$query = $this->db->get_where('customers', array('id'=>$customerId));
return $query->result();
}
at your model.
You need to pass the value as an argument to the function so it can access it.
Ex:
get_customer_records_to_delete($customerid)
{
// now $customerid is accessible
$query = ....;
return $……;
}
You should heavily rely on function parameters. Grab the customer id from the controller and send it to the model. Moreover, you can use row() to get a single result from the database.
Controller:
function confirm_delete_customer(){
$data['title']="Confirm Customer Deletion";
$customerid=$this->uri->segment(3);
//query model to get data results for form
$data=array();
if($query=$this->model_master_data->get_customer_records_to_delete( $customerid)) //you are sending customer id as a parameter here
$data['records']=$query;
$this->load->view("master_data/view_master_data_header",$data);
$this->load->view("master_data/view_master_data_nav");
$this->load->view("master_data/view_content_master_data_confirm_customer_deletion",$data);
$this->load->view("master_data/view_master_data_footer");
}}
Model
function get_customer_records_to_delete($customerid)
{
$query = $this->db->get_where('customers', array("id"=>$customerid)); //you are using the customer id sent from the controller here
return $query->row(); //this will return a single row
}
Old thread but the answer is to declare the variable as "public" in the controller (i.e. public $customerid;), in which case it'll be available to your model. In some cases it's probably safer to explicitly pass as an argument. However, when you have several variables, it's useful to have the option to declare them instead.

Resources