Laravel $request with variable returns null - laravel

I am writing an update methoda for my api. I neede to update requested fields.
So ı am trying to get only requested fields and update them. However, the code below returns me null even thoug I cast $fill to string.
foreach ($fillableFields as $fill){
$customerId->$fill = $request->get("$fill") ;
edit- 1
My code is like below ;
$fillableFields = array('lastname','firstname');
when I dd($fill) it returns me null .

You forgot to call the save() method to update your object :
foreach ($fillableFields as $fill){
$customerId->$fill = $request->get($fill);
$customerId->save();
}

Your method should be.
public function yourMethod(Request $request)
{
try {
foreach ($fillableFields as $fill){
$customerId->$fill = $request->get($fill) ;
}
}
} catch (\Exception $ex) {
}
}

Best way to get request parameters is provided at laravel's official documentation as below.
You can get request parameter based on your specific need.
By using below statment you can get only those perameter you have specified in only attribute as array eg : username, password.
$input = $request->only(['username', 'password']);
If you wantto get all fields excluding particular field than you can define as below with except parameter. eg: by using below it will allow to get all the fields except credit_card.
$input = $request->except('credit_card');
For more information on request parameter please refer official doc url : https://laravel.com/docs/5.4/requests

Related

Get Id Field From Eloquent Laravel

I want get id value from eloquent laravel and passing to variable to insert process. this is my eloquent to get data from siswa table
$siswa = Siswa::where('nis', $row['nis'])->first();
but when accessing id value like $siswa->id I'm getting error
enter image description here
Use this code
if($siswa){
$id=$siswa->id;
}
$siswa variable can be null. Look at its contents with the dd($siswa) command.
To escape the error you can use it like this:
if($siswa)
{
// $siswa not null.
}
You have two ways to fix this.
1/ You can use ->firstOrFail() to display a 404 page in case of your data is not found :
$siswa = Siswa::where('nis', $row['nis'])->firstOrFail();
// if $siswa is NULL, then it will display a 404 page, else it will continue
2/ You can add a simple condition to continue with your data :
$siswa = Siswa::where('nis', $row['nis'])->first();
if ($siswa) {
// then continue
}
First you can $id pass on your public function like
public function show($id)
{
$siswa = Siswa::where('id', $id)->first();
}
You can pass your id on your route

Why Laravel accessor fires on insert?

I'm not sure how they work, I was thinking that accessor fires when you access the attribute, however when I try to insert new record my accessor fires. I store in my database only image_name by removing URL and I use an accessor to include my URL route when I retrieve my image name. I found out that my accessor fires on insert and change my input:
ImageRepository.php
public function save($imageData)
{
$this->model->owner()->associate(auth()->user());
$this->model->type = $imageData->type;
$this->model->image_name = $imageData->image_url;
$this->model->save();
return $this->model;
}
Image.php
public function getImageNameAttribute($value)
{
$filePath = 'my_path';
// check if method was hit
logger()->info('getImageNameAttribute: '.$value);
// return default image if not found
if ($value == '' || $value == null || Str::contains($value, 'no-image.png') || !File::exists(public_path($filePath))) {
return asset('img/no-image.png');
} else {
return asset($filePath);
}
}
Input for $imageData->image_url:
https://some-random-image-url/image-name.jpg
Inserted data:
img/no-image.png
Excepted output (I have a function that extracts the name from URL):
image-name.jpg
When I check the log, I get the message:
getImageNameAttribute: https://some-random-image-url/image-name.jpg
Can someone explain to me if I'm doing something wrong or this is working as pretended?
I did solve the problem, I miss checked. Actually inserted record in my database is correct:
image-name.jpg
But I was checking dd() output after the insert and the value from there was not correct:
img/no-image.png
Because when dd() fires, the accessor is also fired (as we are retrieving data) and as the image was not downloaded it was actually showing correct data.

How i can get the variable data as string like a dd() function in Laravel?

I need to get the request data but i cant get ip, fullUrl and others with all() method (this only print input values), but when i use "dd(request())" this show me all data (i need the data what is printed with dd method, but like a string to save, withour the exception who print this data). Im debbuging my app so i need to save every request data in a log file, something like:
\Log::debug($request)
So,
You can use:
\Log::debug($request->toString());
or alternatively you can use
\Log::debug((string) $request);
The Laravel Request object comes from Illuminate\Http\Request which extends Symfony\Component\HttpFoundation which exposes the following code:
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
$cookieHeader = '';
$cookies = [];
foreach ($this->cookies as $k => $v) {
$cookies[] = $k.'='.$v;
}
if (!empty($cookies)) {
$cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers.
$cookieHeader."\r\n".
$content;
}
__toString() is considered a magic method in PHP.
The __toString() method allows a class to decide how it will react
when it is treated like a string. For example, what echo $obj; will
print. This method must return a string, as otherwise a fatal
E_RECOVERABLE_ERROR level error is emitted.
You can read more about it in the official documentation.
I highly recommend to store just what you want from request data if you don't need all of them, however for both cases you can take a look at serialize and json_encode

Routing with parameters - Laravel

I'm trying to craft a route for a controller that will submit some data to a database. My URL is as follows:
http://example.co.uk/posts/5/edit?type=job
I've tried
Route::post('/posts/{id}/edit?type={role}', 'PostsContoller#store');
but am unsure if this will fly?
Don't add parameters in your route:
Route::post('/posts/{id}/edit', 'PostsContoller#store');
In your controller, just check if parameter exist:
$type = Input::has('type') ? Input::get('type') : null;
Don't worry about HTTP verb, as Input access for all verbs (POST,GET,PUT,DELETE...).
Edit
As pointed out by #Antoine, you can simply specify the default value in the get method
$type = Input::get('type', null);
I don't think that this is the right way to do it.
First way
If you change your route to
Route::post('/posts/{id}/edit/{role?}', 'PostsContoller#store');
You will then call the URL: GET posts/42/edit/job.
your store function in PostsController will be:
public function store($id, $role = null)
{
// some code
}
Second way
You can use another route like:
Route::post('/posts/{id}/edit', 'PostsContoller#store');
You will then call the URL: GET posts/42/edit?type=job
And you can get the type in your store function in PostsController:
public function store($id)
{
// $role will be null if type is not in the URL
$role = Input::get('type', null);
// additional code
}
I would personally go for the second way.

Loading page dynamically from database via id in controller

I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)

Resources