Sahat Riyanto
Sahat Riyanto

Reputation: 135

php - How to show only last word on table Laravel

Hello im really newbie on Laravel. So I really need some help.

I need help on my table. The view from my table contains App\Models\Store and App\Models\Product, but I just want every App\Models\Store and App\Models\ Product to only show as Store and Product

This is my code on my table

<td>
    <label>
        <a href="{!! route('reports.tolink', [$report->id]) !!}" target="_blank">
            {!! $report->reportable_type !!}
        </a>
    </label>
</td>

$report->reportbale_type it contains App\Models\Store and App\Models\Product

and this is my Controller

public function toLink($id)
{
    $report = $this->reportRepository->findWithoutFail($id);

    //get Store Name
    $name = Store::where('id','=',$report->reportable_id)->pluck('name')->all();
    $storename = $name[0];

    //get Store ID
    $idstore = Store::where('id','=',$report->reportable_id)->pluck('id')->all();
    $storeid = $idstore[0];

    if(empty($report))
    {
        Flash::error('Report not found');
        return redirect(route('reports.index'));
    }

    $report_type = class_basename($report->reportable_type);  
    return redirect(env('FRONTEND_URL') ."/".str_slug($report_type)."/$storeid/".str_slug($storename));

}

and this is my table and this is the table

Upvotes: 0

Views: 111

Answers (1)

chanafdo
chanafdo

Reputation: 5124

There are few ways you can do this.

You can use Reflection to get the short name

(new \ReflectionClass($report->reportable_type))->getShortName()

You can explode by \ and get the last item

array_pop(explode('\\', $report->reportable_type))

Using substr and strrpos

substr($report->reportable_type, strrpos($report->reportable_type, '\\') + 1)

You can use one of the above methods and add a getter to your Report model.

public function getReportableTypeNameAttribute()
{
    return (new \ReflectionClass($this->reportable_type))->getShortName();
}

which will allow you to call $report->reportable_type_name in your views.

Upvotes: 1

Related Questions