Php Laravel pass variable from controller to model - php

I'm very new to laravel and I'm really struggling here.
So the thing that i am trying to to is , pass the {wildcard} to in a DB query that's in the model
My Code
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Product extends Model
{
protected $table = "product";
public $timestamps = false;
public function scopeSingleProduct($id){
$products = DB::select("SELECT * FROM product WHERE id = '$id'");
return $products;
}
}
Controller
public function show($id){
$product = Product::SingleProduct($id);
return view('products.product',compact("product"));
}
View
{{ $product }}
So my code basically works if i set $id to a static number in the model file e.g. 1,2,3,4 etc. but it just doesn't seem to work properly here, can someone tell me what i am doing wrong?

TRY THIS
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Product extends Model
{
protected $table = "product";
public $timestamps = false;
//create relationships, that's it, no need to write queries
}
Controller
public function show(Request $request){
//$request->id is the product id, you can pass it through query string or by post
if($request->id>0){
$product = Product::where('id', $request->id)->first();
return view('products.product',compact("product"));
}
}
View
{{ $product }}

Related

Laravel - Eloquent Relationship not working One to Many relationship

I have two models with One-to-Many relationship. I want to display data with relationship in blade.
Products Table
Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
Categories Table
Table name = categories
PrimaryKey = cat_id
Products Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class productsModel extends Model
{
//code...
protected $table = 'products';
protected $primaryKey = 'pro_id';
// Every Products Belongs To One Category
public function category()
{
# code...
return $this->belongsTo('APP\abcModel','cat_id');
}
}
Categories Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class categoryModel extends Model
{
//code...
protected $table = 'categories';
protected $primaryKey = 'cat_id';
// One Category Has Many Products
public function products()
{
# code...
return $this->hasMany('App\productsModel','cat_id','pro_id');
}
}
Controller Code
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
//code...
public function products($category_id='')
{
# code...
$data["products"] = productsModel::where
('cat_id',$category_id)
->get();
$data["categories"] = productsModel::where
('cat_id',$category_id)->first()->category;
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found
Seems that sometimes you have App, sometimes APP, while PHP is not case sensitive on class names, you might use an operating system (Linux?) that is case sensitive in terms of file names.
I would recommend to have only App everywhere, your error message clearly indicates: APP.
You can clearly see in your model files the namespace is written as "namespace App;"
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore "App\categoryModel".
Your code should be as follows:
public function category()
{
# code...
return $this->belongsTo('App\categoryModel','cat_id');
}
Also a sincere request, as #alithedeveloper mentioned please follow PSR standards for writing code.
public function category()
{
return $this->belongsTo(abcModel::class,'cat_id');
}
public function products()
{
return $this->hasMany(productsModel::class,'cat_id');
}

PHP Laravel save model properties via constructor

I am trying to simply save a model to the database via a controller without setting the fields directly but instead having them set in the constructor of said object.
Here is the class handling the logic. If the commented out line
//$todoItem->item = $todo; is uncommented, it works fine and saves whatever is entered in $todo in the database. However, I would like to set that value in the constructor of the task object and not need to manually specify it. I found this question: Laravel with Eloquent doesn't save model properties on database suggesting I could set the property as protected and have it work, but that still does not.
NewTodo.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class NewTodo extends Controller
{
public function saveTodoItem(Request $request)
{
$todo = $request->input('content');
$todoItem = new \App\Task($todo);
//$todoItem->item = $todo;
$todoItem->save();
return view('testview', ['name' => $todoItem->getItem()]);
}
}
Task.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $item = null;
function __construct($newItem)
{
$this->item = $newItem;
}
function getItem()
{
return $this->item;
}
}
Summary, database entry being stored as blank unless $todo->item is manually set when from what I can $todo->item is being set in the constructor.
You don't need to specify these in the constructor. You can use Mass Assignment
Model:
class Task extends Model
{
protected $fillable = ['item'];
}
Controller:
class NewTodo extends Controller
{
public function saveTodoItem(Request $request)
{
$todo = $request->input('content');
$todoItem = new \App\Task::create(['item' => $todo]);
return view('testview', ['name' => $todoItem->getItem()]);
}
}

Laravel - nested relationship shows null

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);

Laravel Destroy() is not removing any record from DB

Database Image
This is my controller's index method. When i run the code it does nothing.
public function index()
{
Customer::destroy(1);
return view('customer');
}
Model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model {
protected $guarded = [];
public $timestamps=false;
}
Try using delete instead of destroy like this:
Customer::findOrFail(1)->delete();
or you can try directly from database using eloquent query builder:
Customer::where('id', 1)->delete();
You can also write your code like this
public function getDeleteTag($id)
{
DB::table('tags')
->where('id','=',$id)
->delete();
return Response::json(['message' => 'Tag has been deleted successfully!']);
}

Eloquent Relationship

Why am I getting this error for such a simple relationship query?
Call to undefined method Illuminate\Database\Query\Builder::country()
I just want to get a list of lookup values from my lookup table called pc_country. I have even included the namespaces!
Controller;
$tableName = $postcode_tablename->dataset; //eg 201502_postcode
$country = PostcodeExtract::fromTable($tableName)
->country() //this is generating the error!
->distinct()
->select('description')
->get();
var_dump($country);
exit;
Country Model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
protected $connection = 'postcodes';
public $table = 'pc_country';
protected $fillable = ['description', 'country_id', 'code'];
public function postcodeExtract()
{
return $this->hasMany('App\Models\PostcodeExtract');
}
}
PostCode Extract Model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
protected $fillable = ['country'];
public function scopeFromTable($query, $tableName)
{
return $query->from($tableName);
}
public function country()
{
return $this->belongsTo('App\Model\Country');
}
}
My 201502_postcode table has a country_id and my pc_country table has a id field for it to do the lookup on. Is that correct? I don't see the problem...
You used fromTable method(scope) it returns eloquent query builder so your relations wont be available. Consider same code without calling that method.
If you want to change table of model create an instance and then call setTable method on the created instance then use your instance to query
$instance = new PostCodeExtract();
$instance->setTable ("table");
$country = $instance->country()->........
Sorry im on mobile couldn't provide good example code but you can achieve it with this method

Categories