Trying to get property of non-object - Laravel 5

Trying to get property of non-object - Laravel 5

I'm trying to echo out the name of the user in my article and I'm getting the ErrorException: Trying to get property of non-object. My codes:
Models
1. News

    class News extends Model
    {
      public function postedBy()
      {
         return $this->belongsTo('App\User');
      }
      protected $table = 'news';
      protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
    }

2. User

    class User extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;

        protected $table = 'users';

        protected $fillable = ['name', 'email', 'password'];

        protected $hidden = ['password', 'remember_token'];

    }
Schema
table users
enter image description here
table news
enter image description here
Controller
public function showArticle($slug)
    {
        $article = News::where('slug', $slug)->firstOrFail();
        return view('article', compact('article'));
    }
Blade
{{ $article->postedBy->name }}
When I try to remove name in the blade {{ $article->postedBy }} it outputs the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field name in my table and a User model. Am I missing something?

Answer:
I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:
First, as suggested by Jimmy Zoto, my code in blade from $article->poster->name to $article->poster['name']. Next is to add a second parameter in my belongsTo, from return $this->belongsTo('App\User'); to return $this->belongsTo('App\User', 'user_id'); in which user_idis my foreign key in the news table.
Thanks for all your help!

copy, file_get_contents, file_put_contents doesn't get full content in new file

copy, file_get_contents, file_put_contents doesn't get full content in new file

I'm trying to download a file that exists on different server and move it to my new server.
I've tried
$file = file_get_contents("https://exampleurl.com/file/download.txt");
file_put_contents("C:/directory/to/report/data.csv", $file);
as well
$remote_file_url = "https://exampleurl.com/file/download.txt";
$local_file = C:/directory/to/report/data.csv;
$copy = copy( $remote_file_url, $local_file );
But the file never completes, it cuts off towards the end of the file. When I download the file directly from the url it's complete everytime.
I'm looking for a way to make sure the file is downloaded completely

Answer:
Use Curl request generally file_get_contents timeout which causes this sort of errors and only the partial content gets loaded. Try this:
$ch=curl_init("https://exampleurl.com/file/download.txt"); //create a c url session
$timeout=300; //set time limit here depends upon the operations being done on the remote server currently its 5mins
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //set timeout for request
$content = curl_exec($ch);//execute request
if($content)
{
    $localfile = fopen("path to local file", "w"); //create or open a existing file
    if(fwrite($localfile , $content)) //write data received
        echo "success";
    else
        echo "unable to write file";
    fclose($localfile ); //close the file

}
else //error occured while executing the request on the remote server
    echo "Request Failed";


phalcon shows directory list following the tutorial with wamp server

phalcon shows directory list following the tutorial with wamp server

I've gone through phalcon's documentation and followed the tutorial provided on the official site:https://docs.phalconphp.com/en/latest/reference/tutorial.html
The problem is when I browse the project (localhost/tutorial) it shows me the directory list as
app/
public/
What am I doing wrong?

Answer:
The .htaccess file for the phalcon directory structure assumes you're working at the web root, not a subdirectory. You'd need to adjust your .htaccess file accordingly if you're not going to follow their proposed directory structure. The .htaccess file they give you is designed to redirect all traffic to the web root to your /public directory thus essentially hiding the /app directory from the web. Try placing their suggested web root .htaccess file in your tutorial directory and add a line RewriteBase /tutorial/. Then place their 2nd .htaccess file in your /tutorial/public directory adjusting its RewriteBase to RewriteBase /tutorial/public/.
Alternatively, you can avoid their public directory altogether and use a safer and faster directory structure, due to avoiding extra RewriteRules, albeit less convenient, by placing your app directory below the web root and adjust your PHP to use either dirname(__DIR__) or .. to refer to the parent directory when attempting to locate your app directory.
A final approach would be to create a subdomain on your localhost, http://tutorial.localhost/, yes localhost subdomains are a great solution for allowing web root access for multiple projects without stepping on each other's toes, then you'd edit your hosts file to add a record for the fake domain mapping it to 127.0.0.1, the same as localhost. Then edit your apache config file adding a virtual host for the subdomain mapping it to a specific directory to use as your web root for that subdomain, reload apache, and presto.

Split php with loop logic

Split php with loop logic

Hello i have a logic question to make my tests finish This is my array
Array ( 
[0] => Array (
  [id] => 1,
  [p] => 150,
  [w] => 120,
),
[1] => Array (
  [id] => 2,
  [p] => 10,
  [w] => 20,
),
[2] => Array (
  [id] => 3,
  [p] => 70,
  [w] => 10,
),
[3] => Array (
  [id] => 4,
  [p] => 100,
  [w] => 45,
),
[4] => Array (
  [id] => 5,
  [p] => 110,
  [w] => 500,
)
)
Update the code
$pt = 0;
foreach($data as $k => $plist){ 
    $pl[] = $plist['id'];
    $pt += $plist['p'];
    if($pt >= 250) break; 
}
// Get filter max p 250
foreach($data $k => $dat){  
    foreach($pl as $paa => $pat){
        unset($data[$paa]); // Delete list key of Data
    }
    $jres[] = array("id" => $dat['id'],"p" => $dat['p'], "w" => $dat['w']);
}
// callback function and filter that will be printed only
foreach($jres as $k => $dat){   
    foreach($data as $paa => $pat){
        unset($jres[$paa]); // Delete list key of JRES
    }
}   
foreach($jres as $k => $dat){
    $subtotal += $dat['p'];
}
$subs = $subtotal + $pt;
end($pl);         
$end = key($pl); 
if($subs > 250){
    unset($pl[$end]); // delete one key if total **p** sum total **price * w ** if above 250 will delete one key    
}
$pack = '<table class="table">
    <thead>
        <h3 style="background:#D8D8D8;">Package 1</h3>
        <tr>
            <td class="right">P</td>
            <td class="right">W</td>
        </tr>
    </thead><tbody>';
foreach($jres as $k => $dat){
$subtotal += $dat['p'];
$subw += $dat['w'];
$list .='<tr>
            <td class="right">$'.$dat['p'].'</td>
            <td class="right">'.$dat['w'].$k.' gram</td>
        </tr>';
    foreach($data as $dat2 => $pat){
        if($k == $dat2) unset($data[$k]); // Delete key from data
    }
}
$gtotal = $subw * $sfee + $subtotal;
$total =    '<tr>
            <th class="right" colspan="2"> Subtotal: </th>
            <th class="right"> $'.$subtotal.' </th>
        </tr>
        <tr>
            <th class="right" colspan="2">Shipping Cost ['.$subw.'g]: </th>
            <th class="right"> $'.$subw * $sfee.' </th>
        </tr>
        <tr>
            <th class="right" colspan="2"> Grandtotal: </th>
            <th class="right"> $'.$gtotal.' </th>
        </tr>
        <tr>
            <th class="right"></th>
            <th class="right"></th>
        </tr>
  </tbody>
</table>';
The goal is how to find smallest "w" in a View split
Max of "p" per split view if total sum is 250
Price /w is 0.25 will be sum with total of p
So i have try some logic with loop but it so complicated and not work
Can you help me to write the logic of this?
my code above just displaying first split view.
sample output i want it like this:
First Split
| id| w | p |
|  2| 20| 10|
|  3| 10| 70|
|  4| 45|100|
| stotal|180|
| wtotal|18.75| // $w = 20 + 10 + 45 * 0.25;
| gtotal|198.75| 

 SecondSplit
| id| w | p |
|  1|120|150|
| stotal|150|
| wtotal| 30| // $w = 120 * 0.25;
|Gtotal |180| 

 Third Split
| id| w | p |
|  5|500|110|
| stotal|110|
| wtotal|125| // $w = 500 * 0.25;
|Gtotal |235| 

Answer:

This will find the lowest value from your array:
<?php

$Arrays = Array ( 
'0' => Array (
  'p' => 150,
  'w' => 120,
),
'1' => Array (
  'p' => 10,
  'w' => 20,
),
'2' => Array (
  'p' => 70,
  'w' => 10,
),
'3' => Array (
  'p' => 100,
  'w' => 45,
),
'4' => Array (
  'p' => 110,
  'w' => 500,
)
);

$Encode = json_encode($Arrays);

$Decoded = json_decode($Encode);



foreach($Decoded as $Item){
$Num[] = $Item->w;

}
echo min($Num); //Will echo 10

Popular Posts

Popular Posts