Delete data from the table after renaming column Laravel 5.8 - php

Recently I've started with Laravel 5.8 and I'm trying to make the delete button which will delete row from the database. But before I create the button, I've Already Change the column id name in the table from id to id_book, the problem is Laravel still get the id-data, not id_book, and raise an error
like this
**Column not found: 1054 Unknown column 'books.id'**
this is button's code:
<form action="/hapus/{{ $book->id_book }}" method="POST">
#method('DELETE')
#csrf
<input type="submit" value="Hapus">
</form>
this is the Controller's Method:
public function hapus($id_book){
$book = Books::find($id_book);
$book->id;
if($book->gambar = 1){
Storage::delete($book->gambar);
$book->delete();
return redirect('/books');
}
else{
$book->delete();
return redirect('/books');
}
the column in tables is:
id_book (previously is id),
name,
image,
category,
description
thank for help, this is my model after fixing this problem:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Books extends Model
{
protected $table = "books";
protected $primaryKey = "id_book";//solution
protected $fillable = [
'title',
'images',
'category',
'description'
];
}

Related

Laravel 8 - Base table or view not found: 1146 Table 'laravel8.brand' doesn't exist

I've been searching the web for quite a long time and I have tried adding the protected $table = "brands"; to my Brand Model as seen here:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
protected $table = "brands";
use HasFactory;
protected $fillable = [
'brand_name',
'brand_image'
];
}
Then on my controller I have the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Brand;
use Illuminate\Support\Carbon;
class BrandController extends Controller
{
public function AllBrand(){
$brands = Brand::latest()->paginate(2);
return view('admin.brand.index', compact('brands'));
}
public function StoreBrand(Request $request){
$validatedData = $request->validate([
'brand_name' => 'required|unique:brand|min:4',
'brand_image' => 'required|mimes:jpg,jpeg,png',
],
[
'brand_name.required' => 'Please input brand name',
'brand_image.min' => 'Brand longer than 4 Characters'
]);
$brand_image = $request->file('brand_image');
$name_gen = hexdec(uniqid());
$img_ext = strtolower($brand_image->getClientOriginalExtension());
$img_name = $name_gen.'.'.$img_ext;
$upload_location = 'images/brand/';
$publish_image = $upload_location.$img_name;
$brand_image->move($upload_location,$img_name);
Brand::insert([
'brand_name' => $request->brand_name,
'brand_image' => $publish_image,
'created_at' => Carbon::now()
]);
return Redirect()->back()->with('success', 'Brand added successfully!');
}
}
Passing this through my routes:
// For Brand Route
Route::get('/brand/all', [BrandController::class, 'AllBrand'])->name('all.brand');
Route::post('/brand/add', [BrandController::class, 'StoreBrand'])->name('store.brand');
Which I also used on my form inside views/admin/brand folder:
<form action="{{ route('store.brand') }}" method="POST" enctype="multipart/form-data">
#csrf
<input type="text" name="brand_name" placeholder="Brand name"/>
#error('brand_name')
<span style="color: red; font-weight: bold;"> {{ $message }}</span>
#enderror
My database table is named brands but adding protected $table = "brands"; did not solve this. I even tried to re-migrate and do this all over again but nothing seems to work at all.
Are there anymore ways to solve this issue? I keep on getting the SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel8.brand' doesn't exist (SQL: select count(*) as aggregate from brandwherebrand_name = Bx LLC) error whenever I am adding a new brand.
Please help!
the problem is not in storing Brand, but in validation:
in your validation:
'brand_name' => 'required|unique:brand|min:4',
this told Laravel to make sure of brand name uniqueness in 'brand' table, so when the query committed, you see that error.
this validation should be:
'brand_name' => 'required|unique:brands|min:4',
Instead of specifying the table name directly, you may specify the Eloquent model which should be used to determine the table name:
'brand_name' => 'required|unique:App\Models\Brand|min:4',
Ref:https://laravel.com/docs/8.x/validation#rule-unique

Laravel 7 : trying to get the name instead of id

I'm trying to get the client name , address ect.. based on their relationship, but when I am trying to get the name for exaple i get the error Trying to get property of 'name' of a non-object.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Client;
class Evaluation extends Model
{
protected $table = 'evaluations';
protected $fillable = [
'expert',
];
public function client() {
return $this->belongsTo(Client::class);
}
}
Controller
public function index()
{
$evaluations = Evaluation::with('client')->get();
$users= auth()->user();
return view('evaluation.index', ['evaluations' => $evaluations]);
}
view
#if (count($evaluations) < 1)
<h1>Nici o evaluare nu a fost gasita.</h1>
#else
#foreach ($evaluations as $evaluation)
<tr>
<td class="pl-1">{{$evaluation->id}}</td>
<td class="pl-1">{{$evaluation->expert}}</td>
<td class="pl-1">{{$evaluation->gram1}}</td>
<td class="pl-1">{{$evaluation->client_id}}</td>
#php
dd($evaluation->client_id->nume)
#endphp
<td> Printeaza</td>
</tr>
#endforeach
#endif
An I also have to mention that in my table is nume instead of name it's no english project.
SOLVED, Relationship and all there was good, all I Needed to do was to create an input hidded for taking the id and add the Id on protected $fillable on client model not on evaluation model. It's work and in the view you have to call it like {{$evaluation->client->nume}}, "->client->" = is the relationship that you called. And I SOLVED even the Foreign key problem, in my create_evaluations_table the client_id column was bigInteger and in my create_clients_table the id of client that I wanted to associate was integer. All you need to do if you will have this error is to make them identically like if the id in the table that you want to associate is integer you need to save the integer there also.

Laravel store DB

I have a little problem.. When I´m trying to store in a database in laravel it´s show me an error like this
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'usuario' in 'field list' (SQL: insert into `tipificaciones` (`usuario`, `origen`, `estado`, `nombreCliente`, `caso`, `venta`, `palabraClave`, `updated_at`, `fecha`) values (Supervisor, Leads, 1, ssd, 129308jk, 1, sdañldaskñasd, 2020-06-05 10:58:58, 2020-06-05 10:58:58))"
When i see my DB this Column exist, I verify the connection to DB was successfull becouse in another view I return info for another table.
This is my model:
<?php
namespace App\modelo;
use Illuminate\Database\Eloquent\Model;
class TipificacionesModel extends Model
{
protected $table = 'tipificaciones';
protected $fillable = ['id','usuario', 'origen', 'estado', 'nombreCliente', 'caso', 'venta', 'palabraClave'];
const CREATED_AT = 'fecha';
}
And my Controller
public function store(Request $request)
{
TipificacionesModel::create([
'usuario'=>$request['usuario'],
'origen'=>$request['origen'],
'estado'=>$request['estado'],
'nombreCliente'=>$request['nombreCliente'],
'caso'=>$request['caso'],
'venta'=>$request['venta'],
'palabraClave'=>$request['palabraClave'],
]);
return("true");
}
My database
1
How I can fix this
Thanks for colaboration!

sync intermediate table in laravel error: Field doesn't have a default value

I am having trouble with syncing the intermediate table in laravel 5.5.
The post blog data that came from the request is saving...but when sync the tags i get this error:
"SQLSTATE[HY000]: General error: 1364 Field 'TagID' doesn't have a default value (SQL: insert into `blog_post_tag` (`PostID`) values (13))"
Let me explain what i have:
There are 3 tables: blog_posts, blog_tags, blog_post_tag (the intermediate table)
In BlogPost model:
protected $table = 'blog_posts';
protected $primaryKey = 'PostID';
public function tags(){
return $this->belongsToMany('App\BlogTag', 'blog_post_tag', 'PostID', 'PostID');
}
and BlogTag model:
protected $table = 'blog_tags';
protected $primaryKey = 'TagID';
// a tag can be found in multiple posts
public function posts(){
return $this->belongsToMany('App\BlogPost', 'blog_post_tag', 'TagID', 'TagID');
}
In BLogController where i have one method that save or update the post:
The savePost method:
// check if update or new
// validate data
// save the post - until here it`s ok
// syncronize tags - here comes the problems :)
if(isset($request->PostID) && $request->PostID != 0) {
// update post; check if the user delete all the tags for the current post
if(isset($request->tags)){
// without the true - which is default - is going to remove all the id`s and put it again
$post->tags()->sync($request->tags, true);
}
else
{
// it will remove all the associations (syncs) and is not gonna put anything!
$post->tags()->sync(array(), true);
}
} else {
// new post; use the sync method to sync the id`s in the blog_post_tag table
$post->tags()->sync($request->tags, false);
}
The $request->tags is an array with selected tags(TagsIDs):
<select class="form-control select2-multi" name="tags[]" multiple="multiple">
#foreach($tags as $tag)
<option value="{{ $tag->TagID }}">{{ $tag->Name }}</option>
#endforeach
</select>
I don't understand what i did wrong? Why is complaining that 'TagID' doesn't have a default value. If i don't send any tags there is no error. The Error is only when update or new post.
You do have problems with customization of the column names of the keys on the table.
The third argument is the foreign key name of the model on which you
are defining the relationship, while the fourth argument is the
foreign key name of the model that you are joining to
Update your BlogPost model
protected $table = 'blog_posts';
protected $primaryKey = 'PostID';
public function tags(){
return $this->belongsToMany('App\BlogTag', 'blog_post_tag', 'PostID', 'TagID');
}
BlogTag model:
protected $table = 'blog_tags';
protected $primaryKey = 'TagID';
// a tag can be found in multiple posts
public function posts(){
return $this->belongsToMany('App\BlogPost', 'blog_post_tag', 'TagID', 'PostID');
}
Laravel Doc
Let me know if you have any problems with this..

Laravel Model renaming MySQL table to plural on query

I am using a model to query a remote MySQL DB and when I run the query, Laravel is trying to connect to the plural version of the table that I need it to connect to. The table's name is activity and the error I get is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'health.activities' doesn't exist (SQL: select * from `activities`)
I just built the model for this using artisan make:model Activity so I am not sure what is going on. Here is my model:
<?php
namespace App;
use DB;
use Role;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model
{
private $activity;
function __construct()
{
$this->activity = DB::connection('mysql_remote')->table('activity');
}
}
Here is my controller:
public function getDashboard()
{
$data = [
'page_title' => 'Dashboard',
'users' => User::getUser(),
'test' => Activity::get(),
];
return view('dashboard.dashboard', $data);
}
Anyone have any idea why this is happening?
Models expect the table to be named the plural of the name of the Model, in this case the plural of Activitiy is activities which is the table name it expects. If it's different, you need to add a table property to set the name of the table.
In your model, add the following...
protected $table = 'activity';

Categories