update title in laravel - php

public function updateMovie(Request $request, $id)
{
$request->title;
$movie = DB::connection('mysql2')->select('UPDATE cb_video SET title='.$request->title.' WHERE videoid=' . $id);
return response()->json(['status' => 'success', 'data' => $movie]);
}
I am trying to update title in db but its throwing me error of
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'WHERE
videoid=1449' at line 1 (SQL: UPDATE cb_video SET title= WHERE
videoid=1449)
what can I do?

there are many better ways in laravel than what you are doing you could use query builder or eloquent to do your task and in a secure way
for example
public function updateMovie(Request $request, $id)
{
$movie = Your_Movie_Modal::findbyId($id);
$movie->title = $request->title;
$movie->update();
return response()->json(['status' => 'success', 'data' => $movie]);
}
and as I can see in your error it mean that you are not sending the title in the request

I hope you find this helpful
$title = 'New Title';
DB::table('table_name')->where('id', $id)->update(['title' => $title]);
Thanks

DB::connection('mysql2')->table('cb_video')
->where('videoid', $id)
->update(['title' => $request->title]);

Related

Method App\\Http\\Controllers\\SalesmanController::show does not exist

I'm using laravel 8 on api call it is giving such type of error
public function getSalesman(){
$salesman = Salesman::where('deleted_at', '=', null)->get(['id', 'name']);
return response()->json([
'salesman' => $salesman,
]);
}
may be you have not show method in this controller!

CakePHP ignore Record not found in table exception

There is no record with ID 0 on purpos. And I'm doing
$id = 0;
try {
$object = $this->MyModel->get($id);
} catch(Exception $e){
//Nothing
}
And I still get the exception thrown "Record not found in table".
How can I ignore, that there is no record with the given ID with get($id) and avoid the exception?
$this->MyModel->find('all', ['conditions' => ['id' => $id]])->first(); seems to be the shortest code without getting an error on non-existence of an element.
The other problem was, that I used Exception instead of the correct \Exception, that's why the error was thrown despite the try-catch-block.
You can also try making the relationship a LEFT join.
Insde MyModelTable.php
$this->MyModel->belongsTo('ParentTable', [
'foreignKey' => 'parent_id',
'joinType' => 'LEFT',
]);
Why not using if statement?
$id = 0;
$object = [];
if ($id){
$object = $this->MyModel->get($id);
} else{
$object = [];
}

"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null

I'm using Laravel and trying to build a gallery, i'm testing the upload of a file to a db but i when i click submit i get the error
" Illuminate \ Database \ QueryException (23000)
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
I've set up a GalleryController and the code is as follows
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class GalleryController extends Controller
{
// List Galleries
public function index (){
//Render View
return view ('gallery/index');
}
// Show Create From
public function create(){
//Render View
return view ('gallery/create');
}
// Store Gallery
public function store(Request $request){
// Get Request Input
$name = $request->input ('name');
$description = $request->input ('description');
$cover_image = $request->input ('cover_image');
$owner_id = 1;
// Check Image Upload
if($cover_image){
$cover_image_filename = $cover_image->getClientOriginalName();
$cover_image->move(public_path('images'), $cover_image_filename);
} else {
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')->insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image,
'owner_id' => $owner_id,
]
);
//Redirect
return \Redirect::route('gallery.index')-> with('message', 'Gallery Created');
}
//Show Gallery Photos
public function show($id){
die ($id);
`
The main.blade.php calls the code using
# if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
# endif;
My .env DB is set to root and password is blank too.
If any more info is needed please advise.
Thanks
I think you have two error:
1) description be null because fo your input was come null or in your view file it has another name
you may do this set default value?
$description = ($request->input ('description')) ? $request->input('description'): "description";
2) your second error is you save temporary image file name
use this instead
//Insert Gallery
DB::table('galleries')->insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id,
]
);

Delete item with ajax from session in laravel 5.4, respond with 500 internal server error

I have this code to push products into array session in laravel 5.4
public function agregarACarrito(Request $request)
{
$producto = new Producto();
$producto = Producto::with('marca')
->where('id', '=', $request->parametros)
->get();
$request->session()->push('session_products', $producto);
return "Producto eliminado";
}
So, i want to delete an item using AJAX, this is my code right now:
public function borrarDeCarrito(Request $request){
$productos = $request->session()->pull('session_products');
foreach($productos as $key => $producto) {
if ($request->parametros == $producto->id) {
unset($productos[$key]);
break;
}
}
$request->session()->put('session_products', $productos);
echo"¡Product removed!";
}
I get a 500 internal server error and in the laravel error log i'm getting
'Exception' with message 'Property [id] does not exist on this collection
instance.
This is my ajax code
function borrarDeCarrito(id){
var parametros=id;
$.ajax({
data:{parametros:parametros},
url:'/borrarDeCarrito',
type:'post',
success:function(data){
//console.log(data);
alert(data);
}
});
}
¿what i'm doing wrong ?
The problem is you are pulling an unregistered index from your session.
$request->session()->push('session_products',$producto);
In the code above, you push session_products to your session but you pull $request->parametros from your session on which you didn't register.
You can only pull session_products from $request->session(), and here's a quick fix
public function borrarDeCarrito(Request $request){
$productos = $request->session()->pull('session_products');
foreach($productos as $key => $producto) {
if ($request->parametros == $producto->id) {
unset($productos[$key]);
break;
}
}
$request->session()->put('session_products', $productos);
}
UPDATE:
$producto = Producto::with('marca')
->where('id', '=', $request->parametros)
->get();
'Exception' with message 'Property [id] does not exist on this collection instance.
With the codes above you are trying to get 1 row by referencing its id, but you called ->get() which is expected to return a multiple collection of Productos.
And after you put that on your session, the structure becomes like this:
session_products = [
0 => [0 => [name => 'productname', ...]]
]
Instead of:
session_products = [
0 => [name => 'productname', ..]
]
You should use ->first() when you only want to get a single row.
To fix it, simply:
$producto = Producto::where('id', '=', $request->parametros)
->with('marca')
->first();

how to prevent getting message:Trying to get property of non-object when id is not found

now I have this controller which gets id from db and than list som information from db. but when I go to database and delete the data manually, the controller can't find the id anymore and it returns :Trying to get property of non-object
with planti of privet information. my conde is something like below:
public function saveChanges(Request $request){
$id=$request->input('id');
$this->validate($request, [
'title' => 'required',
'body' => 'required|min:2'
]);
$post=Post::where('id',$id)->first();
if($post->id == $id){
$post->title = $request['title'];
$post->postBody = $request['body'];
if ($post->update())
{
return response()->json([
'type'=>1,
'newtitle'=>$post->title,
'newbody'=>$post->postBody
]);
}
else{
return response()->json(['type'=>0]);
}
}
else {
echo"404";
}
}
the thing I don't like here is going for the id directly like this:
$post=Post::where('id',$id)->first();
I don't have much idea about laravel so do you think I may prevent this situation by any chance?
As suggested, check first if a post was found before trying to access a property:
$post = Post::where('id',$id)->first();
if ($post instanceof Post && $post->id == $id) {
// ...
}
For reference, see:
http://php.net/manual/en/language.operators.type.php
First you should check if object Post exists, for example by function is_object()
http://php.net/is_object

Categories