How to insert data into mysql database using laravel - mysql

I'm new to Laravel and I want to insert data into the database.
class Test1Controller extends Controller {
public function index(Request $req)
{
$item = $req->input('item');
$name = $req->input('name');
$data=array('item'=>$item,'name'=>$name);
DB::table('test1')->insert($data)
$view = view('common.test1');
$obj = DB::table('test1')->get();
$view->obj = $obj;
return $view;
}
and this is my route file code
Route::post('/test/test1/index/','Controller#index');
I got an error
Call to undefined method Illuminate\Support\Facades\Request::input()

try to include this library at the top of your controller
use Illuminate\Http\Request;

Related

Pass two variable to method in Laravel

i want to find post by slug also in url ..
but the comments must be found by post_id
Controller
public function post($slug,$id)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$id)->get();
return view('content.post',compact('post','comments'));
}
Route
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
public function post($slug)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
Here you go:
Get post_id from the $post itself.
public function post($slug){
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get();
...
}
You can use Route Model Binding to ensure that routes will find your model based on the provided key.
Your Post model will require that you add the following method:
public function getRouteKeyName()
{
return 'slug';
}
Then, in your routes, you can just refer the model directly, and binding will happen automatically:
public function post(App\Post $post)
{
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
This enables you to to use the following route:
Route::get('post/{post}', 'PagesController#post')->name('post.show');
Now, additionally, to ease up your reference of the comments, add them as relations to your Post model:
public function comments()
{
return $this->hasMany(Comment::class);
}
and your Comment model:
public function post()
{
return $this->belongsTo(Post::class);
}
This will allow you to shorten your controller method even more:
public function post(App\Post $post)
{
return view('content.post',compact('post'));
}
and in your Blade view do the following instead:
#foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
#endforeach
in web.php:
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
in controller:
public function post($slug)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
return view('content.post',compact('post','comments'));
}

Yii2 pass query result to a action in another controller

I'm trying to insert record into my audit table upon update of record in any other table. For example, if a user update his profile I want to store the old record and the newly updated record in my audit table. For this in my user model I'm trying to use beforeSave() and pass the value to my audit controller
public function beforeSave($insert)
{
if((parent::beforeSave($insert))){
// Place your custom code here
$query = DepCustomer::findOne($this->customer_id);
Yii::$app->runAction('audit-trial/createaudit', ['query' => $query]);
return true;
}
}
And the action code in audit controller for now
public function actionCreateaudit($query)
{
$model = new Audit();
$model->old = '';
foreach($query as $name => $value){
//$temp = $name .': '. $value.', ';
//$contentBefore[] = $temp;
$audit->old = $audit->old.$name .': '. $value. ', ';
}
// I've not yet any other code for now I'm trying to get the old value
$model->save();
}
I'm getting 404 not found error. What do I need to change in my code to make it work? Thank you!
instead of runAction() . If you want to perform operation on another model, prefer to create a static function in that model (in your case Audit model) to save the data
public function beforeSave($insert)
{
if((parent::beforeSave($insert))){
// Place your custom code here
$query = DepCustomer::findOne($this->customer_id);
Audit::saveOldDetails($query);
return true;
}
}
and write saveOldDetails function in Audit Model
public static saveOldDetails($query){
// your business logic here
}
Refer this link
http://www.yiiframework.com/doc-2.0/yii-base-controller.html#runAction()-detail

professional way add data in database laravel 5.2

what is the professional way insert record in database.
i am using laravel 5.2.
i'm new in laravel.
class students extends Controller
{
public function index()
{
$insertData = array(
"name" => Input::get("name"),
"detail" => Input::get("detail"),
"token_key" => Input::get("_token")
);
return view('student');
}
public function fees()
{
$record = array(
"p_name" => Input::get("name"),
"p_fees" => Input::get("fees"),
"p_detail" => Input::get("detail")
);
return view('fee');
}
}
stander able way?
You should use mass assignment. Fill $fillable array inside your model and use this:
Model::create($insertData);
public function store_student(Request $request)
{
$student = new Student;
$student->name = $request->name;
$student->detail = $request->details
$student->save();
return view('student');
}
public function store_fee(Request $request)
{
$fee = new Fee;
$fee->p_name = $request->name;
$fee->p_fee = $request->fees;
$fee->p_detail = $request->details
$fee->save();
return view('fee');
}
I suggest you to read this from Laravel official guide.
However you can do it like this:
DB::table('tablename')->insert($insertData);

How to use Request->all() with Eloquent models

I have a lumen application where I need to store incoming JSON Request. If I write a code like this:
public function store(Request $request)
{
if ($request->isJson())
{
$data = $request->all();
$transaction = new Transaction();
if (array_key_exists('amount', $data))
$transaction->amount = $data['amount'];
if (array_key_exists('typology', $data))
$transaction->typology = $data['typology'];
$result = $transaction->isValid();
if($result === TRUE )
{
$transaction->save();
return $this->response->created();
}
return $this->response->errorBadRequest($result);
}
return $this->response->errorBadRequest();
}
It works perfectly. But use Request in that mode is boring because I have to check every input field to insert them to my model. Is there a fast way to send request to model?
You can do mass assignment to Eloquent models, but you need to first set the fields on your model that you want to allow to be mass assignable. In your model, set your $fillable array:
class Transaction extends Model {
protected $fillable = ['amount', 'typology'];
}
This will allow the amount and typology to be mass assignable. What this means is that you can assign them through the methods that accept arrays (such as the constructor, or the fill() method).
An example using the constructor:
$data = $request->all();
$transaction = new Transaction($data);
$result = $transaction->isValid();
An example using fill():
$data = $request->all();
$transaction = new Transaction();
$transaction->fill($data);
$result = $transaction->isValid();
You can either use fill method or the constructor. First you must include all mass assignable properties in fillable property of your model
Method 1 (Use constructor)
$transaction = new Transaction($request->all());
Method 2 (Use fill method)
$transaction = new Transaction();
$transaction->fill($request->all());
Create your TransactionRequest with rules extends FormRequest
public function store(TransactionRequest $request)
{
$transaction = new Transaction($request->validated());
$transaction->save();
}

How to dynamically return API JSON from the database and store JSON in MySQL in Laravel 5.1

I am currently developing an api for my site to work with google maps. I have successfully developed an api with help from the community. But it only outputs a single page. I need it to be dynamic, because results will be based off of input from the user. As it stands my controller looks like this
<?php
namespace App\Http\Controllers;
use App\Post;
use App\Http\Requests;
class ApiController extends Controller
{
public function index() {
$results = [];
foreach (Post::all() as $post)
{
$results[] = [
'id' => $post->id,
'marketname' => $post->subtitle,
];
}
return ['results' => $results];
}
}
but this isn't dynamic.
I was thinking of copying my search and modifying it. it looks like this
<?php
namespace App\Http\Controllers;
use App\Jobs\TagIndexData;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Video;
use App\Tag;
use App\Http\Controllers\Controller;
class TagController extends Controller
{
public function index(Request $request)
{
$query = $request->get('q');
$posts = Post::where('title', 'LIKE', "%{$query}%")
->orwhere('subtitle', 'LIKE', "%{$query}%")->get();
$videos = Video::where('title', 'LIKE', "%{$query}%")
->orwhere('subtitle', 'LIKE', "%{$query}%")->get();
$tag = $request->get('tag');
$data = $this->dispatch(new TagIndexData($tag));
$layout = $tag ? Tag::layout($tag) : 'tags.layouts.index';
return view($layout, $data)->withPosts($posts)->withVideos($videos);
}
}
But I don't understand how to store json in mysql nor how to query it and output it Any help would be greatly appreciated.
To be clear on what I want. I want a person to enter their zipcode or address and then return a google map populated with markers indicating nearby events.
I am trying to modify a tutorial I did using a farmers market api mashed up with googles. Part of the javascript looks like this
accessURL="http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + userZip/address;
where userZip/address is input that I want to use to populate the google map
any advice on how I should structure this is welcomed
Returning JSON from the controller is pretty straight forward. Simply return the collection:
public function index() {
$posts = Post::all();
return $posts;
}
Or if you only need to return certain fields, use select():
public function index() {
$posts = Post::select(['id', 'subtitle as marketname'])->get();
return $posts;
}