Cron Job doesn't work on CPanle using Laravel Project - laravel

I'm trying to run a schedule task on cpanel.
So I'm using the following code :
Command : notify.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Mail\NotifyContratExpire;
use Mail;
use Carbon\Carbon;
use App\Models\Projet_Casting;
use App\Models\Filiale;
class notify extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'emails:send';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send Emails notify to all users for contrats expirés';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
$today_date = Carbon::now()->addDays(60);
$contrat_email = Projet_Casting::join('contrats','contrats.id_contrat','=','projets_castings.id_contrat')->leftjoin('projets','projets.id_projet','=','projets_castings.id_projet')->join('castings','castings.id_casting','=','contrats.id_casting')->join('filiales','projets.id_filiale','=','filiales.id_filiale')->where('contrats.actif',1)->where('contrats.date_fin_contrat', '<=', $today_date)->distinct('filiales.id_filiale')->get();
$emails = array();
foreach($contrat_email as $key) {
$emails[] = json_decode($key->adm_email);
}
$email_send = array();
foreach ($emails as $key3 => $value) {
$filiale =Filiale::where('adm_email', json_encode($value))->select('filiales.id_filiale')->value('filiales.id_filiale');
$contras = Projet_Casting::join('contrats','contrats.id_contrat','=','projets_castings.id_contrat')->leftjoin('projets','projets.id_projet','=','projets_castings.id_projet')->join('castings','castings.id_casting','=','contrats.id_casting')->where('contrats.actif',1)->where('contrats.date_fin_contrat', '<=', $today_date)->where('projets.id_filiale',$filiale)->get();
foreach($value as $val =>$v){
Mail::to($v)->send(new NotifyContratExpire($contras));
}
}
}
}
MailController : NotifyContratExpire
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class NotifyContratExpire extends Mailable
{
use Queueable, SerializesModels;
public $contras;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($contras)
{
$this->contras = $contras;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject("contrats")->view('Template_Mails.template_email')->with('contras',$this->contras);
}
}
And kernel.php :
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Mail;
use Illuminate\Console\Command;
use App\Mail\NotifyContratExpire;
use Carbon\Carbon;
use App\Models\Projet_Casting;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
/*'\App\Console\Commands\notify'*/
Commands\notify::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
$schedule->command('emails:send')->everyMinute()->withoutOverlapping(60);
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
And the email view :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<table class="data-table data-table-standard responsive nowrap"
data-order="[[ 1, "desc" ]]">
<thead>
<tr>
<th>numero_contrat</th>
<th>numero_projet</th>
<th>casting</th>
<th>casting</th>
</tr>
</thead>
<tbody>
#foreach($contras as $contra)
<tr>
<td>
<p class="list-item-heading">{{$contra->numero_contrat}}</p>
</td>
<td>
<p class="text-muted">{{$contra ->numero_projet}}</p>
</td>
<td>
<p class="text-muted">{{$contra->nom}}</p>
</td>
<td>
<p class="text-muted">{{$contra->prenom}}</p>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</body>
</html>
On cpanel I have the following structure :
And I created a cron JOV for everyMinute with the following command :
/usr/local/bin/php /home/current_user/laravel/artisan schedule:run
the mails are not sent and I do not know where the error is or how to display the errors to know how to solve this problem, when I run the execution in localhost, it works very well and the emails are sent.
If you have any idea , please help

You can try this
/path/to/php /path-to-your-project/artisan schedule:run >>/dev/null 2>&1

Related

Laravel Livewire unable to parse eloquent relationship with pagination on template

I am having issue with livewire template rendering with Relationship-Eloquent with paginate method.
Livewire component:
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
use App\Http\Controllers\AllUsersController;
use Livewire\WithPagination;
class DatatableComponent extends Component
{
use WithPagination;
/**
* #var parent object
* #property AllUsersController has to be replace using laravel Stubs
*/
protected $parent = AllUsersController::class;
/**
* #var int
*/
public $perPage = 1;
/**
* #var cities
*/
public $cities;
/**
* #var states
*/
public $states;
/**
* #var string
*/
public $page_title = 'Users';
/**
* #var string
*/
public $page_description = '';
/**
* #var array
*/
public $users;
/**
* This used to set the initial value of the parent model.
*
* #return default
*/
public function mount()
{
/** #todo initialize data using read method */
$this->read();
}
/**
* This used to initialize the data .
* #return initial object
* #todo This has to be replaced by the other parent controller objects
*/
protected function read()
{
/** #todo - set all public properties */
$this->parent = new $this->parent;
$this->states = $this->parent->getStates();
$this->cities = $this->parent->getCities();
$this->users = User::with(['logs' => function($query){
$query->with('distinctMeta');
}],'logsMeta','activity')->paginate($this->perPage);
}
/**
* This used to return component.
*
* #param void public property
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function render()
{
return view('livewire.datatable-component');
}
}
Steps which i followed.
when i checked the $this->users its returning the user object. but while accessing public $users property on template its returning error.
Error :
Undefined property: Livewire\CompilerEngineForIgnition::$files
Template:
<div class="card card-custom">
<div class="card-body">
{{-- moving form to partials --}}
#include('livewire._partials.search')
{{-- end move --}}
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>{{ __('Email') }}</th>
</tr>
</thead>
<thead>
<tr>
#foreach($users as $index => $user)
<td>{{ $user->tualog->email }}</td>
#endforeach
</tr>
</thead>
</table>
{{ $users->links() }}
</div>
</div>
Main issue - is unable to use paginate without toArray() method. but when i used toArray() on template {{ $users->links() }} method not working.
if anyone solved this issue please help with that.
Thanks in Advance
as Remul stated, you can't assign objects to public properties in a livewire component. Remove the $users public property and instead assign it in the render() method:
public function render()
{
$users = User::with([
'logs' => function($query) {
$query->with('distinctMeta');
},
'logsMeta',
'activity'
])
->paginate($this->perPage);
return view('livewire.datatable-component', [
'users' => $users
]);
}
I have solved it by using local property for collection like this.
protected $collection
and assigning
$this->collection = $users = User::with([
'logs' => function($query) {
$query->with('distinctMeta');
},
'logsMeta',
'activity'
])
->paginate($this->perPage);
I have changed render method with
public function render()
{
return view('livewire.datatable-component',['users' =>$this->collection]);
}

Laravel DataTables doesn't show any results

I was following this guide to show all partners in my admin section: https://yajrabox.com/docs/laravel-datatables/master/quick-starter
Unfortunately, there are no errors, but I don't see also the list with all items. There are results in the database, but for me, it seems it is not making the query, that's why there are no results (in the debuggbar i don't see a query with the 'partners' table).
route.php
Route::get('partners', [PartnerController::class, 'index'])->name('partners.index');
PartnerController:
namespace App\Domains\Partner\Http\Controllers\Backend;
use App\Domains\Partner\DataTable\PartnersDataTable;
use App\Domains\Partner\Models\Partner;
use App\Domains\Partner\Services\PartnerService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PartnerController extends Controller
{
public function index(PartnersDataTable $dataTable)
{
return $dataTable->render('backend.partner.index');
}
}
PartnersDataTable:
namespace App\Domains\Partner\DataTable;
use App\Domains\Partner\Models\Partner;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
class PartnersDataTable extends DataTable
{
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query)
{
return datatables()
->eloquent($query);
}
public function query(Partner $model)
{
return $model->newQuery();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->setTableId('partners-table')
->columns($this->getColumns())
->minifiedAjax()
->dom('Bfrtip')
->orderBy(1)
->buttons(
Button::make('create'),
Button::make('export'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
Column::make('id'),
Column::make('title'),
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'Users_' . date('YmdHis');
}
}
index.blade.php:
#extends('backend.layouts.app')
#section('title', __('Partners'))
#section('breadcrumb-links')
#endsection
#section('content')
<x-backend.card>
<x-slot name="header">
#lang('Partners')
</x-slot>
#if ($logged_in_user->hasAllAccess())
<x-slot name="headerActions">
<x-utils.link
icon="c-icon cil-plus"
class="card-header-action"
:href="route('admin.partners.create')"
:text="__('Create partner')"
/>
</x-slot>
#endif
<x-slot name="body">
{!! $dataTable->table() !!}
</x-slot>
</x-backend.card>
#endsection
#push('after-scripts')
<script src="{{ asset('vendor/datatables/buttons.server-side.js') }}"></script>
{{$dataTable->scripts()}}
#endpush
Here is what is $dataTable->scripts() producing:
<script src="http://kitty/vendor/datatables/buttons.server-side.js"></script>
<script type="text/javascript">$(function(){window.LaravelDataTables=window.LaravelDataTables||{};window.LaravelDataTables["partners-table"]=$("#partners-table").DataTable({"serverSide":true,"processing":true,"ajax":{"url":"http:\/\/kitty\/admin\/partners","type":"GET","data":function(data) {
for (var i = 0, len = data.columns.length; i < len; i++) {
if (!data.columns[i].search.value) delete data.columns[i].search;
if (data.columns[i].searchable === true) delete data.columns[i].searchable;
if (data.columns[i].orderable === true) delete data.columns[i].orderable;
if (data.columns[i].data === data.columns[i].name) delete data.columns[i].name;
}
delete data.search.regex;}},"columns":[{"data":"id","name":"id","title":"Id","orderable":true,"searchable":true},{"data":"title","name":"title","title":"Title","orderable":true,"searchable":true}],"dom":"Bfrtip","order":[[1,"desc"]],"buttons":[{"extend":"create"},{"extend":"export"},{"extend":"print"},{"extend":"reset"},{"extend":"reload"}]});});
</script>
the reason why your data isn't displaying on the table is because of this line of code:
->buttons(
Button::make('create'),
Button::make('export'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
);
comment this line of code and the data will be displayed properly.

laravel 8 markdown email image not showing

I'm dispatching a markdown email using the Laravel's mailable class.
Here's the following code for the mailable.
<?php
namespace App\Mail;
use App\traits\Mail\RecordMailTrait;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Laravel\Spark\Invitation;
class ExistingUserCompanyInviteMail extends Mailable
{
use Queueable, SerializesModels, RecordMailTrait;
/**
* Create a new message instance.
*
* #return void
*/
protected $invite;
public $inviter;
public $view = 'email.invitation-to-current-user';
public function __construct(Invitation $invite, User $inviter)
{
$this->invite = $invite;
$this->inviter = $inviter;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$invitation = $this->invite;
$view = $this->view;
$to = $this->to[0]['address'];
$sent_by_email = $this->inviter->email;
$this->withSwiftMessage(function ($message) use($invitation, $view, $to, $sent_by_email){
$message->view = $view;
$message->sent_to_email = $to;
$message->sent_by_email = $sent_by_email;
$message->mailable_type = Invitation::class;
$message->mailable_id = $invitation->id;
});
return $this->markdown($this->view,['invitation' => $this->invite, 'inviter' => $this->inviter, 'entity' => $this->invite->team->name, 'url' => url('/home/invitations')])->subject("Invitation");
}
}
I get the email in my inbox, with the correct text and styling, however not the image, it doesn't load as it should.
Here's the code for the HTML:
<tr>
<td class="header">
<a href="{{ $url }}" style="display: inline-block;">
<img src="{{ asset('/img/logo.svg')}}" class="logo" alt="logo1">
</a>
</td>
</tr>
This is the URL I get from the image in the sent email:
https://ci3.googleusercontent.com/proxy/8oh80_LJVyfK50ZObX23alnA8vhDzf3vXWJC_kHVgccnfzs-zSher-TbH9fO4RcDWjTQ5s8c_q3V6qc=s0-d-e1-ft#http://core-hosp.test/img/logo.svg
logo does not show (image of email)

Class 'App\Http\Controllers\App\Article' not found Laravel 5.6

I have a "basic" problem, but I can't figure where.
I have a problem between the controller and the model.
I went on the Internet and I saw a lot of "Class 'App\Http\Controllers\App{something}' not found" solved problem, but none worked for me.
Could it be because I did a copy-past form my native project?
I'm only looking for the "index" part. I can't work on the rest since I can't see what I'm doing.
MyController:
<?php
namespace App;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Article;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
session_start();
$article = App\Article::Blog();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
session_start();
// si je reçois des données de formulaire,
if (isset($_POST['titre'], $_POST['description'], $_POST['contenu'])
){
$admin = Add();
// si la création a réussi,
if ($add) {
//rediriger vers
header('location: /Chef/Controleur/controleur-blog.php');
echo "Well done!". '<br>';
echo "You have add an article!";
}
}
else {
// afficher le formulaire
echo "Error. Please try again.";
require __DIR__.'/Controleur/controleur_piedpage.php';
}
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
require __DIR__.'/../Modele/modele.php';
$article = Article();
// si je reçois des données de formulaire,
if (isset($_POST['titre'], $_POST['description'], $_POST['contenu'])){
$admin = Edit();
// si la création a réussi,
if ($edit) {
//rediriger vers
header('location: /Chef/Controleur/controleur-blog.php');
echo "You have edit an article!";
}
}
else {
// afficher le formulaire
require __DIR__.'/Controleur/controleur-entete.php';
require __DIR__.'/Controleur/controleur-recherche.php';
require __DIR__.'/../Vue/edit.php';
echo "Error. Please try again.";
require __DIR__.'/Controleur/controleur_piedpage.php';
}
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
require __DIR__.'/../Modele/modele.php';
$admin = Delete();
$article = Article();
if ($delete) {
//rediriger vers
header('location: /Chef/Controleur/controleur-blog.php');
}
else {
// afficher le formulaire
require __DIR__.'/Controleur/controleur-entete.php';
require __DIR__.'/Controleur/controleur-recherche.php';
require __DIR__.'/../Vue/delete.php';
echo "Error. Please try again.";
require __DIR__.'/Controleur/controleur_piedpage.php';
}
}
}
My Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
function Blog() {
if(isset($_POST['register'])) if(('role'== 0) && ('role' == 1)) {
$todoread = [];
$pdo = prepareStatement('SELECT * FROM article ORDER BY id DESC LIMIT 100');
$pdo->execute();
$todoread = $pdo->fetchAll(PDO::FETCH_ASSOC);
return $todoread;
}
}
function Edit(){
$pdo_statement = prepareStatement('UPDATE article
SET titre=:titre, description=:description, contenu =:contenu
WHERE id=:id');
$pdo_statement->bindParam(':id', $_GET['id']);
$pdo_statement->bindParam(':titre', $_POST['titre']);
$pdo_statement->bindParam(':description', $_POST['description']);
$pdo_statement->bindParam(':contenu', $_POST['contenu']);
$pdo_statement->execute();
return true;
}
function Article(){
if(isset($_GET['id'])) {
$sql = "SELECT * FROM article WHERE id = :id";
$article = prepareStatement($sql);
$article->bindParam(':id', $_GET['id']);
$article->execute();
return $article->fetch();
}
}
function Delete() {
if (isset($_POST['submit'])) {
$pdo_statement = prepareStatement('DELETE FROM article WHERE id =:id');
$pdo_statement->bindParam(':id', $_GET['id']);
$pdo_statement->execute();
$pdo_statement->fetchAll(PDO::FETCH_ASSOC);
return true;
}
}
function Add(){
if (isset($_POST['submit'])) {
$pdo_statement = prepareStatement(
'INSERT INTO article (titre, description, contenu)
VALUES (:titre, :description, :contenu)');
$pdo_statement->bindParam(':titre', $_POST['titre']);
$pdo_statement->bindParam(':description', $_POST['description']);
$pdo_statement->bindParam(':contenu', $_POST['contenu']);
$pdo_statement->execute();
return true;
}
}
}
The View:
#extends('layouts.app')
#section('title', 'Blog')
#section('content')
<br>
<br>
<br>
<?php if(!isset($_SESSION['nom'])): ?>
<h1 class="center"> Welcome to my blog ! </h1>
<h2 class="center"> Tips, tutorials and more on chatbots, artificials intelligence </h2>
<p>
To access the blog, please register yourself <br>
You'll find the link to the registration here or you can login here.
</p>
<?php else: ?>
<h1 class="center"> Welcome to my blog <?= $_SESSION ['nom'] ?> ! </h1>
<h2 class="center"> Enjoy the tips and tutorials of this blog! </h2>
<br>
<button class="ui small black button"> Add an article </button>
<br>
<?php
foreach ($blog as $ligne) {
?>
<br>
<button class="ui small black button"> Edit the article</button>
<button class="ui small black button"> Delete the article </button> <br>
<?php echo $ligne['titre'].'<br>'; ?><br>
<?php echo $ligne['description'].'<br>'; ?><br>
<?php echo $ligne['contenu'].'<br>'; ?> <br> <br> <!-- créer un template : https://openclassrooms.com/courses/adoptez-une-architecture-mvc-en-php/creer-un-template-de-page !-->
<?php
}
?>
<br>
<?php endif; ?>
#endsection
Thank you for your help!!
To fix your issue, change:
<?php
namespace App;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Article;
In your controller to:
<?php
namespace App\Http\Controllers; // <- removing duplicate namespace
use Illuminate\Http\Request;
use App\Article; // <- Case sensitive, use App\, not app\
Other than that, I would really encourage you to read the documentation of Laravel, because this code is not really using Laravel.
You do not have to use session_start() as in Laravel you have Session.
You do not have to work with superglobals as $_POST, because you can use Laravel's Request objects.
You should not handle request data in your models, that's what your controller and/or services are for, this layer (request data) should not 'bleed' into your models like this.
You are using PDO statements, and totally bypass Laravel's Eloquent ORM.
I also see a lot of conditional requires, something that you should not do if you were using Laravel's service container.
With all of this, you are practically skipping every bit of functionality of Laravel and you are basically using the entire framework just for routing.

Laravel Object error

i'm trying to add users with specified roles into database , an error indicates
"ErrorException in 748460238d8f66b0fe4acb25c19f24f04b548bd9.php line 25:
Trying to get property of non-object (View: ..\views\admin\users\index.blade.php)".
below are the UserModel, index.blade.php and the controller.
What's wrong ?
Great thanks
<?php
namespace App\Http\Controllers;
use App\Role;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\UsersRequest;
class AdminUsersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$users=User::all();
return view('admin.users.index',compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
$roles = Role::lists('name','id')->all();
return view('admin.users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(UsersRequest $request)
{
//
User::create($request->all());
//return $request->all();
return redirect('/admin/users');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
return view('admin.users.show');
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
return view('admin.users.edit');
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token'
];
public function role(){
return $this->belongsTo('App\Role');
}
}
#extends('layouts.admin')
#section('content')
<h1>Users</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Created</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
#if($users)
#foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role->name }}</td>
<td>{{ $user->is_active == 1 ? 'Active' : 'No active' }}</td>
<td>{{ $user->created_at }}</td>
<td>{{ $user->updated_at }}</td>
</tr>
#endforeach
#endif
</tbody>
</table>
#stop
Migrations schema:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('roles');
}
}
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->index()->unsigned()->nullabe();
$table->integer('is_active')->default(0);
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
In your blade file, try this:
#foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
#if($user->role)
{{ $user->role->name }}
#else
No role defined
#endif
</td>
<td>{{ $user->is_active == 1 ? 'Active' : 'No active' }}</td>
<td>{{ $user->created_at }}</td>
<td>{{ $user->updated_at }}</td>
</tr>
#endforeach
Update function role() in User model like below:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token'
];
public function role(){
return $this->belongsTo('App\Role','role_id');
}
}
Add role_id and is_active in $fillable inside User model to save those record in users table.
protected $fillable = [
'name', 'email', 'password','role_id','is_active',
];
Why don't you check what is on line 25 of 748460238d8f66b0fe4acb25c19f24f04b548bd9.php?. Find the file and check it.
My first assumption is that you're not using User::with('role')->get() instead of User::all(). You can't access $user->role->name without the relation loaded.

Resources