I am using laravel backpack package and while edit and delete or preview operation I am getting the below error.
No query results for model [App\Models\Customer] record id
I have included the model. What am I am missing?
And one more thing the record id which is showing in the error it is not present in the table, But the backpack list interface is showing. why?
And this table is a master. Any CRUD operation will happen only for its own tbl only not affecting any other tbl.
Below is controller
<?PHP
namespace App\Http\Controllers\Admin;
use App\Models\Customer;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\CustomerRequest;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use Carbon\Carbon;
class CustomerCrudController extends CrudController
{
use \Backpack\CRUD\app\Http\Controllers\Operations\ListOperation;
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation
{store as traitstore;}
use \Backpack\CRUD\app\Http\Controllers\Operations\UpdateOperation
{update as traitupdate;}
use \Backpack\CRUD\app\Http\Controllers\Operations\DeleteOperation
{destroy as traitDestroy;}
use \Backpack\CRUD\app\Http\Controllers\Operations\ShowOperation;
public function setup()
{
//$this->crud->enableExportButtons();
$this->crud->setModel('App\Models\Customer');
$this->crud->setRoute(config('backpack.base.route_prefix') . '/customer');
$this->crud->setEntityNameStrings('customer', 'customers');
}
protected function setupListOperation()
{
// TODO: remove setFromDb() and manually define Columns, maybe Filters
//$this->crud->setFromDb();
$this->crud->setColumns([
[
'name' => 'company_name',
'label' => 'Company',
'type' => 'text',
],
[
'name' => 'company_address1',
'label' => 'Primary Add',
'type' => 'text',
],
[
'name' => 'primary_contact',
'label' => 'Primary Cont',
'type' => 'text',
],
[
'name' => 'company_city',
'label' => 'city',
'type' => 'text',
]
]);
}
}
Model is
<?PHP
namespace App\Models;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Customer extends Model
{
use CrudTrait, SoftDeletes;
protected $table = 'customers';
protected $primaryKey = "cust_id";
protected $fillable = [
'company_name',
'company_address1',
'company_address2',
'company_city',
'company_zip',
'company_country',
'company_state',
'company_vat',
'company_id',
'primary_contact',
'technical_contact',
'financial_contact',
'cust_def_time_zone',
'created_at',
'updated_at',
'deleted_at' ];
}
edit setupShowOperation function in CustomerCrudController
add this
Customer::withTrashed()->find(\request()->id);
Related
Error when I submit form to insert to database. The problem is why picture does not exist?
Method Illuminate\Http\Request::picture does not exist.
This is my Controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\User;
use File;
class UsersController extends Controller
{
public function registeract(Request $request)
{
$this->validate($request,[
'name' => 'required|alpha',
'email' => 'required|email',
'level' => 'required|alpha',
'picture' => 'required|file|image|mimes:jpeg,jpg,png|max:1048',
'password' => 'required'
]);
// Menyiapkan data gambar yg diupload ke variable $file
$picture = $request->picture('picture');
$file_name = time()."_".$picture->getClientOriginalName();
// Isi dengan nama folder tempat kemana file diupload
$upload_directory = 'p_users';
$picture->move($upload_directory, $file_name);
User::create([
'name' => $request->name,
'email' => $request->email,
'level' => $request->level,
'picture' => $file_name,
'password' => bcrypt($request->password),
'remember_token' => Str::random(60)
]);
return redirect('/ec-admin/users')->with('usrsinsertno', 'Data Inserted Successfully!');
}
}
I don't know therefore can use as Model but I see on youtube that there some people use as model.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'level', 'picture', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Picture method doesn't exist on Laravel's request class.
You need to use $picture = $request->file('picture');
Any methods that appear in your head cannot be used.
There is no method like picture in Laravel, as #amirrezam75 mentioned.
Firstly, you need to check if the file exists. You can then save the file and its name.
Try below code:
if ($request->hasFile('picture')) {
$picture = $request->picture('picture');
$file_name = time()."_".$picture->getClientOriginalName();
}else{
$file_name = null;
}
I have a problem with GraphQL(rebing-graphql)/Larvel app. App works fine when I query normal GraphQL query(single not nested), but when I query nested one, I face "debugMessage":"Cannot return null for non-nullable field \"Make Type.name\".
Normal query which works fine:
{model{id,name}}
Nested query that I want to execute:
{model{id,name,make_id{id,name}}
Where am I made mistake?
Thanks in advance.
Make Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
class Make extends Model
{
use HasFactory;
protected $fillable = [
'name',
'logo',
'website',
];
public function models()
{
return $this->hasMany(\App\Models\Model::class);
}
}
Model Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model as MModel;
class Model extends MModel
{
use HasFactory;
protected $fillable = [
'make_id',
'name',
'website',
];
public function make()
{
return $this->belongsTo(Make::class);
}
}
MakeQuery (Graphql part)
<?php
namespace App\GraphQL\Queries;
use App\Models\Make;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Query;
class MakeQuery extends Query
{
protected $attributes = [
'name' => 'Make Type',
'description' => 'Fetch Make Query'
];
public function args(): array
{
return ["id" => ['type' => Type::int()]];
}
public function type(): type
{
return Type::listOf(GraphQL::type('make'));
}
public function resolve($root, $args)
{
if (isset($args['id'])) {
return Make::where("id",$args['id'])->get();
}
return Make::all();
}
}
MakeType
<?php
namespace App\GraphQL\Types;
use App\Models\Make;
use Rebing\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Type as GraphQLType;
class MakeType extends GraphQLType
{
protected $attributes = [
'name' => 'Make Type',
'description' => 'Make API Type',
'model' => Make::class
];
public function fields(): array
{
return [
"id" => [
'type' => Type::nonNull(Type::int()),
'description' => 'Make ID'
],
"name" => [
'type' => Type::nonNull(Type::string()),
'description' => 'Make ID'
],
"logo" => [
'type' => Type::nonNull(Type::string()),
'description' => 'Make ID'
],
"website" => [
'type' => Type::nonNull(Type::string()),
'description' => 'Make ID'
]
];
}
}
ModelQuery
<?php
namespace App\GraphQL\Queries;
use App\Models\Model;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Facades\GraphQL;
use Rebing\GraphQL\Support\Query;
class ModelQuery extends Query
{
protected $attributes = [
'name' => 'Model Type',
'description' => 'Fetch Model Query'
];
public function args(): array
{
return [
"id" => ['type' => Type::int()]
];
}
public function type(): type
{
return Type::listOf(GraphQL::type('model'));
}
public function resolve($root, $args)
{
if (isset($args['id'])) {
return Model::where("id", $args['id'])->get();
}
return Model::all();
}
}
ModelType
<?php
namespace App\GraphQL\Types;
use App\Models\Make;
use App\Models\Model;
use Rebing\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Type as GraphQLType;
class ModelType extends GraphQLType
{
protected $attributes = [
'name' => 'Model Type',
'description' => 'Model API Type',
'model' => Model::class
];
public function fields(): array
{
return [
"id" => [
'type' => Type::nonNull(Type::int()),
'description' => 'Model ID'
],
"make_id" => [
'type' => GraphQL::type('make'),
'description' => 'Model_ID'
],
"name" => [
'type' => Type::nonNull(Type::string()),
'description' => 'Model Name'
],
"website" => [
'type' => Type::nonNull(Type::string()),
'description' => 'Model website'
]
];
}
}
There are several things that you have to done to get your code works:
First: Be sure that your tables are full and have valid key relations.
Second: In ModelType change make_id to makeId.
Third: Reload composer autoload with composer dump-autoload.
Finally: In your Model Model it's better to define a column like below:
public function makeId()
{
return $this->belongsTo(Make::class, 'make_id', 'id');
}
I hope these steps would help you.
have an issue
unable to get id from the created model. I check database row created normally
$productStoreLink = ProductStoreLink::create([
'product_id' => $item->id,
'store_id' => $store['id'],
'code' => $store['code']
]);
$productStoreLink->id;
In array dd($productStoreLink)
"product_id" => 1
"store_id" => "2"
"code" => "5411183083684"
"updated_at" => "2021-04-01T09:27:38.000000Z"
"created_at" => "2021-04-01T09:27:38.000000Z"
I have mode. Yeah, this model has extends Pivot, but this is for more difficult operations.
QUESTION:
I wanna receive id from collection after creating a model. $productStoreLink->id in first codeblock.
Real to get id from this model?
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\SoftDeletes;
class ProductStoreLink extends Pivot
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
'id',
'store_id',
'product_id',
'store_id',
'code',
'created_at',
'updated_at',
'deleted_at',
];
public function price()
{
return $this->hasOne('App\Models\ProductStorePrices','product_store_link_id','id');
}
public function prices()
{
return $this->hasMany('App\Models\ProductStorePrices','product_store_link_id','id');
}
}
I am working in laravel-lumen. I have two models. An Organization model and an Apikey model corresponding to an organizations and an apikeys table. The column organization_id in the apikeys table is a foreign key referring to the id field of the organizations table.
The model for organizations looks like
<?php
namespace App;
use App\Apikey
use Illuminate\Database\Eloquent\Model;
Class Organization Extends Model {
public $table = 'organizations';
public $fillable = [
'name',
'contact_name',
'contact_phone',
'contact_email',
'address1',
'state',
'city',
'zip',
'country'
];
public function apikeys()
{
return $this->hasMany('App\Apikey');
}
}
The apikeys model looks like this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
Class Apikey Extends Model {
public $table = 'apikeys';
public $fillable = [
'key',
'secret',
'organization_id',
'permissions'
];
}
organization_id in apikeys is a foreign key in the organizations table that refers to the id field of organizations table.
Now I have a controller that generates the api key given an organization_id and the permissions and fills the apikeys table. It looks like this
<?php
use App\Http\Controllers\Controller;
use App\Apikey;
use Illuminate\Http\Request;
public function generateApiKeyGivenOrganizationId(Request $request)
{
$data = $request->all();
// code for generating api key.
$dd = [
'key' => 'generated encrypted key',
'secret' => 'secret',
'organization_id' => $data['organization_id'],
'permissions' => $data['permissions']
];
$xx = Apikey::create($dd);
return response()->json(['status' => 'ok', 'apikey_id' => $xx->id]);
}
}
I want to test this code. I created two model factories like this.
$factory->define(Organization::class, function ($faker) use ($factory) {
return [
'name' => $faker->name,
'contact_name' => $faker->name,
'contact_phone' => '324567',
'contact_email' => $faker->email,
'address1' => 'xxx',
'state' => 'Newyork',
'city' => 'Newyork',
'country' => 'USA'
];
});
$factory->define(Apikey::class, function ($faker) use ($factory) {
return [
'key' => 'xxx',
'secret' => 'xxxx',
'permissions' =>'111',
'organization_id' => 7
});
My testing function looks like this.
public function testApiKeyGeneration ()
{
factory(App\Organization::class)->create()->each(function($u) {
$data = [
'organization_id' => $u->id,
'permissions' => '111'
];
$this->post('/createapikeyfororg' , $data)
->seeJson(['status' => 'ok']);
});
}
The controller works perfectly. It is only in the testing I am having problems. The url '/createapikeyfororg' is the url that invokes the controller method generateApiKeyGivenOrganizationId(). Is this testing procedure correct? I am yet to try it out and I am asking this question on a Saturday because I am really in a hurry. I am a total novice at testing and I am in a hurry and any help would be appreciated.
I'm trying to find out why when I dd($request->all()) in the store method of my controller everything is correct, however when I send it to the model function register() its no where to be seen.
I'm not quite sure what I'm doing wrong.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function store(Request $request, User $user)
{
$this->authorize('delete', $user);
$this->validate($request, [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
$userRegistered = $user->register(
new User($request->all())
);
if ($userRegistered) {
flash()->success('Success', 'The user has been successfully created!');
} else {
flash()->error('Error', 'The user could not be successfully created!');
}
return redirect()->to(route('users'));
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use SoftDeletes;
/**
* Fillable fields for a user.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'display_name',
'email',
'password',
'role_id'
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function register(User $user)
{
return $user->create([
'first_name' => $user->firstName,
'last_name' => $user->lastName,
'display_name' => $user->displayName,
'email' => $user->emailAdress,
'password' => $user->password,
'role_id' => $user->role
]);
}
}
You've mixed up the formatting of your variables between your request data and your User model.
According to your validation logic, the request data is coming is as camelCase. Yet, according to your $fillable array, the fields on your User model are snake_case. But, even then, in your register method, you're attempting to access the fields on the User model using camelCase.
You haven't given enough information for a definitive answer, but you need to fix the formatting of your variables. For example, change your request fields names from camelCase to snake_case, and make sure you access your fields on the model using snake_case.
You have to pass a list of attributes to "validate" method.
//...
$this->validate($request->all(), [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
One more thing..check if you are using "web" middleware. (Kernel.php => MiddlewareGroups). Add that middleware to your route.