Laravel: Difference between $request->all() and $request->input() - laravel

What is the difference between $request->all() and $request->input()?
According to their documentation, they look very similar to each other:
You may retrieve all of the incoming request's input data as an array using the all method.
You may call the input method without any arguments in order to retrieve all of the input values as an associative array.

input() gets all input values and query string parameters.
all() is like input() but also includes all files.

$request->all()
usage comes if you wish to fetch all data passed as a collection.
Below is an example that gets all data and creates a record in your database table as per model usage.
public function post(Request $request)
{
$post = new Status();
$post->create($request->all());
}
$request->input()
Usage comes if you wish to fetch a variable passed as a single parameter.
Below is an example that gets data and creates a record in your database table as per model usage.
public function post(Request $request)
{
//get data as parameters passed from your form
$title = $request->input('title');
$author = $request->input('author');
//you can save data like this....This is just an example
DB::table('posts')
->insert([
'title' => $title,
'author' => $author,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
}

Related

How do I "json_decode" a single column data after fetch from database in Laravel?

I am saving an array in one column of my database using json_encode as follows and it works:
$service->description = $request->service_description;
$service->image = json_encode($url);
$service->duration = $request->service_delivery_time;
When I fetch the data I get a string. I am fetching using $service = Service::findOrFail($id);. I can decode the individual column as done below and pass it to the view.
$service = Service::findOrFail($id);
$images = json_decode($service->image);
return view('services.show',['service'=>$service , 'images'=>$images]);
What I am asking is, can I decode the images in one query?
Well this is a single query, json_decode runs after the SQL query returned your desired result.
What you can do is add a $casts property to your Service model so Laravel encodes/decodes it automatically for you, then you don't need to store these values with json_encode, just do $service->image = $url, and when you run findOrFail, the image property will already be a decoded json.
protected $casts = [
'image' => 'array',
];
Here's the documentation
You can use $cast or Accessor
1: $cast:
protected $casts = [
'image' => 'array'];
2: Accessor:
public function getImageAttribute()
{
return json_decode($this->attributes['image']);
}

Laravel Coding Practice / Most Optimised Method to Store

Laravel documentation says one should store as follows:
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
However, why not just as follows:
public function store(Request $request)
{
Flight::create($request->all());
}
The above example is quite easy, since it only has one field. But I imagine its rather tedious to do something with many fields and have to assign each one as opposed to just passing the whole $request as in the second example?
First option gives you better control as to what goes into new model. If you store everything from the request then user might inject fields that you don't want to be stored for a new model in your store method.
For example, your flight has column is_top_priority that is declared as fillable in your Flight model, but when creating new flight you want to set only name for you flight (and leave is_top_priority as null or maybe it has default value of 0 in your table). If you write Flight::create($request->all()); then user can inject <input name="is_top_priority" value="1"> and get advantage of your code.
That is why it is not recommended to use fill($request->all()). Use $request->only(...) or assign each needed field manually as provided in your first example.
For example your model have some fields like name, email, password,status and etc.
Request validate name, email and password and if you do this:
Flight::create($request->all());
Client can send with other fields status, but you change status manually. I do this:
Flight::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => $request->get('password'),
'status' =>config('params.flight.status.not_active'),
]);

Simplify store controller method on laravel 5

This is my store method to save a post.
public function store(CreatePostRequest $request)
{
$post = new Post([
'title' => $request['title'],
'content' => Crypt::encrypt($request['content']),
'published_at' => Carbon::now()
]);
$post->user()->associate(Auth::user());
$newPost=Post::create($post->toArray());
$this->syncTags($newPost, $request['tag_list']);
return redirect('posts')->withMessage('Post Saved Successfully !!!');
}
In laracasts tutorial he is just doing a
Article::create($request->all());
I need to do the extra stuff like encrypt, but am i cluttering the method? could it be cleaner?
Do it in the Model. I use the set/get*Attribute() method to change stuff on the fly.
So you could use Article::create($request->all()); then in the model use the fillable array to only autofill what is allowed (such as title, content and published_at).
then use something like (in the model)
function setContentAttribute( $value ){
$this->attributes['content'] = Crypt::encrypt($value);
}
In fact you could also adapt this approach so that the published_at attribute is set to today, or even better use your database to provide now()s time.

passing an array from controller to model in laravel

I want to know that how to pass an array from laravel controller to laravel model .So that i can save them into db using a model . I don't want to make my controllers to heavy for that I am asking for this . When I have been saving form submissions into db where I should put my saving function ? in controller or model?
Laravel has something called Mass Assignment. It let's you pass an associative array and fills the model with those values. To make it work you have to define all the attributes you want to be able to mass assign in your model:
protected $fillable = ['foo', 'bar', 'and', 'much', 'more'];
Now you can just pass an array to the constructor of the model:
$input = [
'foo' => 'value1',
'bar' => 'value2',
'and' => 'value3',
'much' => 'value4',
'more' => 'value5',
];
$model = new Model($input);
$model->save();
Or even shorter, use the create() method which fills the model and directly saves it afterwards:
Model::create($input);
Try this..
//In Model get data from controller
public function functionname($data1, $data2){
//query
}
//In Controller sent data to Model
$data = Modelname::functionname($data1, $data2)->get();

How can i give a where condition before update_batch in codeigniter?

I want to update my table where the input the same input fields names are array and has
add more function which generates the input fields like this:
I want to do update_batch in codeigniter
my model i created a function like this:
This is the code block:
function update_batch_all($tblname,$data=array(),$userid)
{
$this->db->trans_start();
$this->db->where('userid',$userid);
$this->db->update_batch($tblname,$data);
$this->db->trans_complete();
return TRUE;
}
it is not working.
can any one help me that how can i update tables data with update batch that has where condition?
You can read the docs for update_batch() here
Here's the short summary:
You pass in an associative array that has both, your where key, and the update value. As the third parameter to the update_batch() call, you specify which key in your assoc array should be used for the where clause.
For example:
$data = array(
array(
'user_id' => 1,
'name' => 'Foo'
), array(
'user_id' => 2,
'name' => 'Bar'
)
);
$this->db->update_batch($tbl, $data, 'user_id');
Breakdown of arguments passed:$tbl is the table name. $data is the associative array. 'user_id' tells CI that the user_id key in $data is the where clause.
Effect of the above query: Name for user with user_id = 1 gets set to Foo and name for user with user_id=2 gets set to Bar.
In your case, if you want to set the same user_id key in each array with your data array, you can do a quick for loop:
foreach ($data as &$d) {
$d['user_id'] = $user_id;
}
$this->db->update_batch($tbl, $data, 'user_id');
You can use,
$this->db->update_batch($tblname,$data,'user_id');
But all array within data must have a field 'user_id'
eg:
$data=array(
array('user_name'=>'test1','user_id'=>1),
array('user_name'=>'test2','user_id'=>2)
);
You can get more details about update_batch from here

Resources