Call to a member function delete() on null / AdminHomeController.php line 26: - php

Using the multi_auth from laravel 5.3 im trying to make a delete/edit/update button.
Im trying to delete an user from the admin dashboard retrieving information from the users table.
Actually my first problem is with the destroy function.
This is my destroy route:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
This is my controller from admin:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AdminHomeController extends Controller
{
public function __construct()
{
$this->middleware('admin.user');
}
public function index()
{
$users = User::all();
return view("admin-home")->with('users', $users);
}
public function destroy($id)
{
$users = User::find($id);
$users->delete();
Flash::error('El usuario ' . $users->name . '$ ha sido eliminado con exito!');
return redirect()->route('admin-home');
}
}
View with delete button:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="col-sm-offset-2 col-sm-8">
#if (count($users) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Todos los Usuarios
</div>
<div class="panel-body">
<table class="table table-striped user-table">
<thead>
<th>Nombre:</th>
<th> </th>
<th>Email:</th>
<th> </th>
<th>Acciones:</th>
<th> </th>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> </td>
<td>{{ $user->name }}</td>
<td> </td>
<td>{{ $user->email }}</td>
<td> </td>
<td>
<i class="glyphicon glyphicon-trash" aria-hidden="true"></i>
</td >
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</td>
<td> </td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
</div>
</div>
#endsection
Thank you!

Check $id in
$users = User::find($id);
$users->delete();
Object $users is null because user didn't found in database or $id is incorrect

After playing around with the code i found this usefull:
In the view i had 2 buttons the delete and the edit ones, i changed:
{{ route('users.destroy', $user->id) }}
{{ route('users.edit', $user->id) }}
for:
{{ url('users.destroy', $user->id) }}
{{ url('users.edit', $user->id) }}
And now i can see the buttons without any problems, the issue now is the same as before, the function destroy gives me an error.
This is the route that causes the error:
Route::get('{id}',[
'as' => 'admin.destroy',
'uses' => 'AdminHomeController#destroy'
]);
Error: No query results for model [App\User].
This is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And still can't find the issue.. #edwardstock

Related

Laravel 7 - Trait 'Laravel\Sanctum\HasApiTokens' not found

I am working with iframes and I am trying to compare the user's email with the teacher's email with eloquent. That would be the condition to list only the groups of that teacher, but it gives me this error:
Trait 'Laravel\Sanctum\HasApiTokens' not found
This is my function
public function index($id)
{
$email = User::select('email')->where('id', $id)->get();
$groups= DB::table('groups')
->join('teacher_group', 'grupo_profesor.idGrupo', '=', 'groups.idGrupo')
->join('teachers', 'teachers.idTeacher', '=', 'teacher_group.idTeacher')
->join('level_group', 'level_group.idGroup', '=', 'groups.idGroup')
->join('levels', 'levels.idLevel', '=', 'level_group.idLevel')
->join('courses', 'courses.idCourse', '=', 'levels.idCourse')
->join('programs', 'programs.idProgram', '=', 'courses.idProgram')
->where('teachers.email', '=', $email)
->paginate(10);
return view('teacherGroups.index', compact('groups','email'));
}
The sidebar button
<button class="list-group-item list-group-item-action small text-secondary"
onclick="crearTabAndIframe('TeacherGroups','teacherGroups');
Loadiframe('{{ url('Groups/Teacher/'.auth()->user()->id)}}','ifrmTeacherGroups')">
<i class="material-icons">list</i> #lang('menu.List')
</button>
This is the index view
#foreach($groups as $group)
<tr>
<td class="small text-center">{{$group->idGroup}}</td>
<td class="small text-center">{{$group->levelName}} {{$group->courseName}} {{$group->programName}}</td>
<td class="small text-center">{{$group->teacher_name}}</td>
<td class="small text-center">
<div class="row small">
<div >
<!--VIEW-->
<button onclick="seeGroup({{$group->idGroup}})" class="btn btn-sm btn-outline-success">
<i class="material-icons">remove_red_eye</i>
</button>
</div>
</div>
</td>
</tr>
#endforeach
And with the error it shows me this part of my model
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
Try This, looks like you need to install sanctum
composer require laravel/sanctum
I guess SanctumServiceProvider is not automatically registered in your application. To resolve your issue, you should add the service provider manually in config/app.php.
'providers' => [
//...
Laravel\Sanctum\SanctumServiceProvider::class,
];

Tried to using belongsTo in Laravel but its not working

im using Laravel 6.2
I want to make a inventory database system. i have 2 modals Produk and Stock.
in that case, i want to input data p_name and sku from ProdukTable and place it into StockTable using Eloquent ORM.
I tried using belongsTo(),
Here's my modal Produk code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
public $table = 'produk';
protected $primaryKey = 'pid';
protected $fillable = [
'pid',
'p_nama',
'sku',
'p_harga',
'status'
];
}
Here's my modal Stock code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stock extends Model
{
public $table = 'stock';
protected $primaryKey = 'sid';
protected $fillable = [
'sid',
'p_nama',
'sku',
'p_stock_min',
'p_stock',
'status'
];
public function produk()
{
return $this->belongsTo('App\Produk', 'pid');
}
}
My StockController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use App\Produk;
use RealRashid\SweetAlert\Facades\Alert;
class StockController extends Controller
{
public function index()
{
$datas = Stock::paginate(5); // 5 record per pages
return view('stock.list', compact('datas'));
// $datas = Stock::all();
// return $datas;
}
. . . .
}
My View stock.blade
<div class="body">
<div>
<i class="zmdi zmdi-account-add"></i> Tambah Stock
<a style="margin: 2px;" href="{{ route('stock.index')}}" class="btn btn-primary btn-sm"><i class="zmdi zmdi-refresh"></i></a>
</div>
<div class="col-sm-12">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
#endif
</div>
<table class="table table-bordered table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th class="text-center" style="width:5%">#</th>
<th class="text-center" style="width:25%">Nama Produk</th>
<th class="text-center" style="width:10%">SKU Produk</th>
<th class="text-center" style="width:8%">Min. Stock</th>
<th class="text-center" style="width:8%">Stock</th>
<th class="text-center" style="width:10%">Status</th>
<th class="text-center" style="width:10%">Aksi</th>
</tr>
</thead>
<tbody>
#if(!empty($datas) && $datas->count())
#foreach($datas as $data)
<tr>
<th class="text-center">{{ $loop->iteration }}</th>
<td>{{ $data->produk }}</td>
<td>{{ $data->p_nama }}</td>
<td>{{ $data->p_stock_min }}<code> pcs</code></td>
<td>{{ $data->p_stock }}<code> pcs</code></td>
<td class="text-center">{{ $data->status }}</td>
<td class="text-center">
<i class="zmdi zmdi-edit"></i></span>
<i class="zmdi zmdi-delete"></i></span>
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="8">Data tidak ditemukan! Silahkan buat data Stock terlebih dahulu.</td>
</tr>
#endif
</tbody>
</table>
{!! $datas->links() !!}
</div>
Migration Stock
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStocksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stock', function (Blueprint $table) {
$table->bigIncrements('sid');
$table->bigInteger('produk_id')->unsigned();
$table->string('p_nama');
$table->string('sku');
$table->integer('p_stock_min');
$table->integer('p_stock')->nullable();
$table->string('status');
$table->timestamps();
});
Schema::table('stock', function (Blueprint $table) {
$table->foreign('produk_id')->references('pid')->on('produk')
->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stock');
}
}
Response when i add data direct from PMA
[{"sid":1,"produk_id":6,"p_nama":"kopi1","sku":"12345678","p_stock_min":20,"p_stock":800,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"},
{"sid":2,"produk_id":7,"p_nama":"kopi2","sku":"87654321","p_stock_min":20,"p_stock":600,"status":"Aktif","created_at":"2020-11-24 16:37:16","updated_at":"2020-11-24 16:37:16"}]
i dunno where's my mistake ?
just want to add data p_produk into stock table using select form, and when i select it sku data will be generate as same as data on table Produk.
In your Stock model you should put the foreign key in the belongsTo relation. Edit the method like so:
public function produk()
{
return $this->belongsTo('App\Produk', 'produk_id');
}
Using Laravel conventions the relationship produk should be defined as
public function produk()
{
return $this->belongsTo(Produk::class, 'produk_id', 'pid');
}
To dynamically change the value of sky in the readonly input on create.blade.php based on the option selected by the user in select control showing $produk->p_nama:
Give an id to the readonly input for sku
<div class="form-group">
<label for="sku">SKU:</label>
<input type="text" class="form-control form-control-lg" name="sku" id="skuSelected" readonly/>
</div>
Track the option selected in select control
<select class="form-control select2" name="p_name" onChange="setSku(this);">
#foreach($produks as $produk)
<option value="{{ $produk->pid }}">{{ $produk->p_nama }}</option>
#endforeach
</select>
Handle the change in selection via javascript
<script>
function setSku(sel) {
const sku = sel.options[sel.selectedIndex].text;
document.getElementById('skuSelected').value = sku;
}
</script>
because you are not naming your columns on the laravel naming conventions
you have to define it all by yourself if you want to use this naming like this :
public function produk()
{
return $this->belongsTo('App\Produk', 'pid' , 'id');
}
as belongsTo takes $relatedModel , $foreignKey , $ownerKey in a row

Trying to get property 'name' of non-object (View: (...) resources/views/products/index.blade.php)

In table in view with data from products table I am traying to show names from user table but getting this error. I made Laravel relations in models and foreign keys. And added directory in product controller for user model.
Error: Trying to get property 'name' of non-object (View: /home/laravel/web/laravel.swt101.eu/public_html/abonamenty/resources/views/products/index.blade.php)
This is part of my controller for showing product data:
public function index()
{
$user = User::all('name','id');
$products = Product::sortable()->paginate(5);
return view('products.index',compact('products', 'user'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
This is part of view where I am getting this error
<td>{{ $product->user->name }}</td>
This is rest code of this view:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Zarządzanie abonamentami</h2>
</div>
<div class="col-md-4">
<form action="/search2" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
<div class="pull-right">
#can('product-create')
<a class="btn btn-success" href="{{ route('products.create') }}"> Utwórz nowy abonament</a>
#endcan
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th scope="col">#sortablelink('id', 'Numer')</th>
<th scope="col">#sortablelink('name', 'Nazwa usługi')</th>
<th scope="col">#sortablelink('user_id', 'Kontrachent')</th>
<th scope="col">#sortablelink('category', 'Kategoria')</th>
<th scope="col">#sortablelink('launchdate', 'Data uruchomienia')</th>
<th scope="col">#sortablelink('expirationdate', 'Data wygasnięcia')</th>
<th scope="col">#sortablelink('renewalprice', 'Cena odnowienia')</th>
<th width="280px">Akcja</th>
</tr>
#foreach ($products as $product)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->user->name }}</td>
<td>{{ $product->category }}</td>
<td>{{ $product->launchdate }}</td>
<td>{{ $product->expirationdate }}</td>
<td>{{ $product->renewalprice }}</td>
<td>
<form action="{{ route('products.destroy',$product->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Więcej</a>
#can('product-edit')
<a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edytu</a>
#endcan
#csrf
#method('DELETE')
#can('product-delete')
<button type="submit" class="btn btn-danger">Usuń</button>
#endcan
</form>
</td>
</tr>
#endforeach
</table>
{!! $products ?? ''->appends(request()->except('page'))->render() !!}
#endsection
This is my product model:
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use Sortable;
protected $fillable = [
'name', 'detail', 'id', 'created_at', 'updated at', 'category', 'launchdate', 'expirationdate', 'renewalprice', 'user_id', 'billingperiod', 'internalcost', 'status'
];
public $sortable = ['id', 'name', 'created_at', 'updated at', 'category', 'launchdate', 'expirationdate', 'renewalprice', 'category', 'user_id'];
public function user()
{
return $this->belongsTo('App\User','user_id');
}
}
This is my user model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
use Sortable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'surname', 'showname', 'business', 'NIP', 'PESEL', 'address', 'city', 'postalcode', 'phone', 'comments',
];
public $primaryKey = 'id';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public $sortable = ['name',
'email',
'surname',
'showname',
'business',
'address',
'city',
'phone',
'role',
];
public function products()
{
return $this->hasMany('App\Product');
}
public function invoices()
{
return $this->hasMany('App\Invoice');
}
}
The error indicates that $product->user is probably returning null. Maybe not all products are associated with users for some reason.
Find the product id and look it up in the database, to see if it has a user connected.
In product model
you need to replace by this
return $this->belongsTo('App\User','user_id','id')

Eloquent query on relationship table

Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
protected $table = "Adressen";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchAdress($query, $searchTerm)
{
return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
}
public function kontokorrent()
{
return $this->hasOne(Kontokorrent::class, 'Adresse');
}
}
Kontokorrent Model
class Kontokorrent extends Model
{
protected $table = "Kontokorrent";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchKto($query, $searchTerm)
{
return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
}
public function adress()
{
return $this->belongsTo(Adress::class, 'Adresse');
}
}
Controller
class AdressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
$query->where('KtoArt', 'D')
->searchKto('K75688'); // this is working
// -> searchKto($searchTerm); this is NOT working
})->orderBy('Name1')
->searchAdress($searchTerm)
->paginate(60);
return view('adresse.index', compact('adresses', 'searchTerm'));
}
}
The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
#section('content')
<div class="row">
<div class="col-xs-12 col-md-12">
<form role="search" method="GET" action="/adresses">
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">
<div class="input-group-btn">
<button type="submit" class="btn btn-search btn-default">
Suchen...
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Straße</th>
<th>Ort</th>
<th>PLZ</th>
<th>Land</th>
</tr>
</thead>
<tbody>
#if(count($adresses) > 0)
#foreach($adresses as $adress)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>
{{$adress->Anrede}} {{ $adress->Name1}}
#if($adress->kontokorrent)
<small>{{ $adress->kontokorrent->Kto }}</small>
#endif
</td>
<td>{{ $adress->LieferStrasse }}</td>
<td>{{ $adress->LieferOrt }}</td>
<td>{{ $adress->LieferPLZ }}</td>
<td>{{ $adress->LieferLand }}</td>
</tr>
#endforeach
#else
<tr><td colspan="6" class="text-center">Kein Eintrag gefunden.</td></tr>
#endif
</tbody>
</table>
</div>
</div>
{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
#endsection
I don't understand why I get an empty table.

Laravel: Eloquent returning an object I can't iterate over

I have a mySQL DB schema like this:
table RECIPES:
int id, PK;
int salesman_id;
int doctor_id;
date order_date;
int status;
table RECIPE_STATUS:
int id, PK;
int recipe_status_code;
varchar recipe_status_name;
In Laravel I have the following php classes:
AdminRecipesController.php
namespace RatCMS\Controllers;
use App\Http\Controllers\Controller;
use Auth;
use RatCMS\Models\Recipes;
use RatCMS\Models\RecipeStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class AdminRecipesController extends Controller
{
public function index()
{
$recipes = Recipes::with('recipeStatus')->get();
return view('admin.recipes.news', compact('recipes'));
}
}
Recipes.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class Recipes extends Model
{
protected $table = 'RECIPES';
protected $fillable = ['salesman_id', 'doctor_id', 'order_date', 'status'];
public function recipeStatus() {
return $this->hasOne(\RatCMS\Models\RecipeStatus::class, 'recipe_status_code', 'status');
}
}
RecipeStatus.php
<?php
namespace RatCMS\Models;
use Illuminate\Database\Eloquent\Model;
class RecipeStatus extends Model
{
protected $table = 'RECIPE_STATUS';
protected $fillable = [];
public function recipes() {
return $this->belongsTo(\RatCMS\Models\Recipes::class);
}
}
blade view
<div class="box-body">
#include('admin.partials.session_success')
#if($recipes->isEmpty())
<p class="text-center">No recipes available.</p>
#else
<table class="table table-bordered">
<tr>
<th style="width: 10px">#</th>
<th>Salesman</th>
<th>Doctor</th>
<th>Date</th>
<th>Status</th>
<th style="width:100px">Actions</th>
</tr>
#foreach($recipes as $recipe)
{{ $recipe }}
<tr>
<td>{{ $recipe->id }}</td>
<td>{{ $recipe->salesman_id }}</td>
<td>{{ $recipe->doctor_id }}</td>
<td>{{ $recipe->order_date }}</td>
<td>{{ $recipe->recipe_status->recipe_status_name }}</td>
<td>
<form style="display: inline-block" action="{{ url('admin/recipes/' . $recipe->id) }}" method="POST">
{{ csrf_field() }}
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger"><i class="fa fa-close" aria-hidden="true"></i> Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
#endif
</div>
When I do {{ $recipe }} in the view, I get the following result:
{"id":1,"salesman_id":"4","doctor_id":"3","order_date":null,"status":"0","recipe_status":{"id":1,"recipe_status_code":"0","recipe_status_name":"Not Recieved"}}
so there is some data being return by Eloquent regarding the recipe status (Not Recieved text), but when I do {{ $recipe->recipe_status }} it fails every time. Even $recipes['recipe_status'] is no help.
Could someone help? Thanks
Relationship should be belongsTo():
public function recipeStatus() {
return $this->belongsTo(\RatCMS\Models\RecipeStatus::class, 'status', 'recipe_status_code');
}
With correct relationship your code will add relationship data to collection, so you'll be able to get status:
$recipe->recipeStatus->recipe_status_name

Categories