Inserting a variable in sql through laravel - laravel-5

I am trying to insert data into sql in laravel 5
My Code:
$a1=Input::get('username');
$a2=Input::get('reg_no');
DB::insert("INSERT INTO ngosignup VALUES($a1,$a2)");
But I am getting SQL error:
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
'#gmial.com,a,a,a,a,9,a,9814937684,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,N'
at line 1 (SQL: INSERT INTO
ngosignup(name,email,pass,confirmpass,address,city,pin,state,mobile,registration,secretary,dest,firstmember,mobile1,secondmember,mobile2,thirdmember,mobile3,objective,dev1,place1,obj1,dev2,place2,obj2,dev3,place3,obj3)
VALUES(a,amit#gmial.com,a,a,a,a,9,a,9814937684,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL))
PLEASE HELP.

Try Eloquent way.. for example of using your db.. Make a Model for ngosignup table and include it on controller
public function create(\Illuminate\Http\Request $request) {
$input = $this->request->all();
$a1 = $input['username'];
$a2 = $input['reg_no'];
$newngo = new ngosignup; //Replace ngosignup with your Model name.
$newngo->name = $a1; //name and reg_no should be column name
$newngo->reg_no = $a2;
$newngo->save(); //this will add these values into your DB
}
You can do this way.. Easier and Flexible.. You can add validator.. Refer to Laravel docs on their official site :)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ngosignup;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ngosignupController extends Controller
{
public function index() {
$ngo = ngosignup::first(); // this shows first row of table..you can use get() instead of first to get all table as collection.
$data= array(
'ngo ' => $ngo
);
return View('index', $data);
}
Then on Index.Blade.php File.. you can display data from ngosignup table like
{{ $ngo->email }} // replace email with which data to display. if ollection.. use foreach loop to display all data.
Refer to Laravel docs.. they list all methods available..

Related

eloquent get all row of a table and edit a field

I'm a newbie on laravel and I'm trying to use Eloquent to edit a field for all rows of a MySQL table.
So I create that:
<?php
namespace App\Http\Controllers;
use App\Mining;
use DB;
class FrontendController extends Controller{
public function cronDiff(){
$basic = GeneralSettings::first();
$row = Mining::all()->whereStatus(1)->get();
foreach ($row as $coins){
$code = Mining::where('coin_code', $coins->coin_code)->get();
$risultato = difficolta($code);
DB::table['minings']->insert('coin_code' => $code);
}
}
}
And I have a table minings like this:
id->int
name->varchar
coin_code->varchar
coin_diff->varchar
status->tinyint
But I can't update coin_diff using the value of $risultato (taken from other function)
Can you help to find out where I'm wrong?
Thanks.
try to use ->update('coin_code' => $code); instead ->insert
I think this solution would be better:
$minings = DB::table('minings')->get();
$minings->coin_code = $code;
$minings->update();
It should work like that: Mining::update(['coin_code' => $code]) if you have conditions you can chain them before update.
Also, you need to have the columns on models $fillable property. So, i don't know what error do you get but it might be from that.
If you want to update then why are you using insert?!
If you want to update a single row then modify your code
DB::table['minings']->insert('coin_code' => $code);
to
$coins->update(['coin_code' => $risultato]);
And make sure that $risultato have string value

Laravel 5.4 elequent create method generate wrong query

I am trying to insert data in a table using eloquent create method, But data which I have passed not coming in insert query generated by create method. Due to which I am getting a default value error.
Below are the code i have used
Model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class PasswordReset extends Model
{
protected $fillable = ['email', 'token'];
}
Controller :
$content = ['email'=>'test#gmail.com', 'token'=>'1234'];
PasswordReset::create($content);
Error I am getting :
SQLSTATE[HY000]: General error: 1364 Field 'email' doesn't have a default value (SQL: insert into password_resets (updated_at, created_at) values (2018-09-25 16:16:45, 2018-09-25 16:16:45))
Why query in above error does not have 'email' and 'token' fields?
from your comment:
#cbaconnier, Thanks, After looking your comment. I have checked with my code and its having a __construct method without having any code within it and removing this resolve the issue.
If you want to use __construct() on the Model, you need to build it like this
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// your code
}
I think you should create like this
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234'
]);
try this way :
$passwordReset = new PasswordReset();
$passwordReset->email = 'test#gmail.com';
$passwordReset->token = '12345';
$passwordReset->save();
try this i hope work for you :
PasswordReset::create([
'email'=>'test#gmail.com',
'token' => '1234']);

Retrieve all columns from table A and some from table B using laravel eloquent

I am trying to retrieve the thumb image path by joining the images table to the listing table. As such, I have the following query in my controller.
$listings = Listing::select('listings.*, images.path as image_path')
->where('listings.ownerid', '=', $ownerid)
->leftJoin('images', 'listings.thumbId', '=', 'images.id')->get();
After testing out the function, the query fails since laravel interprets the query as
select `listings`.`*, images`.`path` as `image_path` from `listings` left join `images` on `listings`.`thumbId` = `images`.`id` where `listings`.`ownerid` = 1)
Notice the asterisk (*) is joined with the ", images" word making it '*, images'.
The query works fine without laravel's odd typo. How does one fix this issue?
You need to do one change in your query. You are passing raw select fields so you need to use selectRaw() instead of select(). Like
$listings = Listing::selectRaw('listings.*, images.path as image_path')
->where('listings.ownerid', '=', $ownerid)
->leftJoin('images', 'listings.thumbId', '=', 'images.id')->get();
check by try above query.
I suggest you to use Laravel Eloquent Relationships feature. Since your code above is more like Query Builder rather than Eloquent. Let's see the example bellow:
You will have 2 Models, 1 for each table (listings, images):
App\Listing Model:
<?php
...
use App\Image;
class Listing extends Eloquent {
...
protected $table = 'listings';
// define Eloquent Relationship of Listing model to Image model
public function image() {
return $this->belongsTo(Image::class, 'thumbId');
}
...
}
App\Image Model:
<?php
...
use App\Listing;
class Image extends Eloquent {
...
protected $table = 'images';
...
// define Eloquent Relationship of Image model to Listing model
public function listings() {
return $this->hasMany(Listing::class, 'thumbId');
}
}
So how to get the data?
// get all listing data
$listings = Listing::all();
// loop through the data
foreach ($listing as $listing) {
dump($listing->id);
// because we have define the relationship, we can access the related data of image
dump($listing->image->path);
// call $this->image will return related Image model
dump($listing->image);
}
You can see Laravel official documentation for more example and explanation.
Hope it helps.

How to add data to additional column in pivot table in laravel

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user(); and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
You should use attach() like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
Try the save method as:
$user->relations()->save($plan, ['child' => $childid]);
Docs
Both save and attach work. Just that attach will return null while save will return $user object when I try with tinker

Laravel model all() function is not working as intended

I have a model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model {
protected $table = 'contacts';
//
}
And in the controller action
$c= Contact::all();
I am getting the "Whoops, looks like something went wrong." error.
Error detail:
FatalErrorException in ContactController.php line 9:
Class 'App\Http\Controllers\Contact' not found
The table "contacts" exists in the database.
What thing I am missing? Whats wrong here?
Tell your controller where your model is if it is in route of your project then on the top of your controller add
use App\Contact;
Or you may also define it every time
$c = App\Contact::all();
also in your model no need to define a table until it is not different from the plural model name. If your model name is Contact, laravel on its own query contacts table, you should define the table name if the model name is Contact and the table name is somethingElse.
Don't use
$c= Contact::all();
Instead use
$c = \App\Contact::all()
or
$c = new \App\Contact;
$c->all();
This is all that you have to use.
UPDATE: Just after digging in the concepts of OOP, I found this:
<?php
use \App\Contact;
var_dump(Contact::all());

Resources